rtrigoso - 1 year ago 77

Java Question

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;

}

}

}

}

}

Answer Source

Find GCD of l and b. Then number of pieces = (l/gcd) * (b/gcd)

To find GCD check out code here : Java: get greatest common divisor