Find GCD of l and b. Then number of pieces = (l/gcd) * (b/gcd)
for(int j=1; j <= l && j <= b; ++j) {
if(l%j==0 && b%j==0)
gcd = j;
}
printf("%d\n",(l/gcd)*(b/gcd));
题
So I am working on a hackerRank challenge in which the input is the L and B of a piece of bread and the output is supposed to be the amount of perfect square slices (no residual) I can get.
Martha is interviewing at Subway. One of the rounds of the interview requires her to cut a bread of size l * b into smaller identical pieces such that each piece is a square having maximum possible side length with no left over piece of bread.
I feel that my code does the job yet I keep getting errors. Since I can't see what is wrong with it I was hoping for someone to help me point out where I gone wrong.
My code:
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;
}
}
}
}
}
解决方案
Find GCD of l and b. Then number of pieces = (l/gcd) * (b/gcd)
for(int j=1; j <= l && j <= b; ++j) {
if(l%j==0 && b%j==0)
gcd = j;
}
printf("%d\n",(l/gcd)*(b/gcd));
其他提示
Here's the code for the solution of the above problem:
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);
}
}
}