从一块l*b的面包中找出我能做多少片最大的正方形

bwleehnv  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(303)

所以我正在研究一个hackerrank挑战,输入是一片面包的l和b,输出应该是我能得到的完美的正方形切片(没有剩余的)。
玛莎正在地铁面试。其中一轮面试要求她把一个l*b大小的面包切成相同的小块,每个小块都是一个正方形,边长最大,没有剩余的面包。
我觉得我的代码做的工作,但我不断得到错误。因为我看不出有什么问题,所以我希望有人能帮我指出哪里出了问题。
我的代码:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

public static void main(String[] args) {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
    Scanner STDIN = new Scanner(System.in);
    int l = 0;
    int b = 0;
    int count = STDIN.nextInt();

    for(int i = 0; i<count; i++){
        l = STDIN.nextInt();
        b = STDIN.nextInt(); 

        if(l>b){
            check(l,b);
        }
        else if(b>l){
            check(l,b);
        }
        else{
            check(l,b);
        }
        System.out.print("\n");
    }
}

public static boolean square (int n){
    int sqrt = (int) Math.sqrt(n);
    if(sqrt*sqrt == n){
        return true;    
    }
    else{
        return false;
    }
}
public static void check(int first, int second){
    int mult = first*second;

    if(square(first)){
    System.out.print(second);            
    }
    else if(square(second)){
    System.out.print(first);             
    }
    else{
    factors(mult);   
    }    
}
public static void factors(int n){
    //int B = 0;
    //int A = 0;

    for(int i = 1; i<=n; i++){
        if(n%i == 0){            

            if(square((n/i))){
                     System.out.print((i));
                     break;                    
            }
        }

    }
}
}
lymgl2op

lymgl2op1#

下面是解决上述问题的代码:

package subway;

import java.util.Scanner;

public class MarthaProblem {
    public static void main(String[] nag){
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        for(int i=0;i<t;i++){
            if(t>=1 && t<=1000){
                int l = sc.nextInt();
                int b = sc.nextInt();
                if((l>=1 && l<=1000)&&(b>=1 && b<=1000)){
                    System.out.println(calculate(l,b));
                }
            }
        }
    }
    public static int calculate(int l, int b){
        return ((l/(gcd(l,b)))*(b/(gcd(l,b))));
    }

    public static int gcd(int l,int b){
        if(b==0){
            return l;
        }else{
            return gcd(b, l%b);
        }
    }
}
8nuwlpux

8nuwlpux2#

找到l和b的gcd。则件数=(l/gcd)*(b/gcd)
对于(int j=1;j<=l&&j<=b++(日本){

if(l%j==0 && b%j==0)
        gcd = j;
     }
     printf("%d\n",(l/gcd)*(b/gcd));

相关问题