Question:
Need help with Java Errors, So many errors so little time. Short code?
InterventionPRO
2012-04-04 10:35:03 UTC
Need help with Java Errors, So many errors so little time. Short code Please and Thank you!

Consider the problem of finding the Greatest Common Divisor (GCD) of two positive integers a and b. It can be mathematically proved that if b<=a

GCD(a, b) = b, if (a mod b) = 0;
GCD(a, b) = GCD(b, a mod b), if (a mod b) != 0.

Write a recursive function called GCD with signature “public static int GCD(int a, int b)” that returns the greatest common divisor of two positive integers a and b with b <= a. Also write a java program to test your function


MUST use recursion This is my code

public class GCDNO1 {

public static int GCD(int a, int b)
{

if (a mod b == 0)
return b;
else if (a mod b !=0)
return GCD(b, a mod b);
else
return (a-1, GCD(a,b-1));

}

public static void main(String[] args) {

System.out.println("GCD(a,b)= " + GCD(a,b));

}
}

Thank you!
Five answers:
James Bond
2012-04-04 10:46:54 UTC
I did not check logic in your problem. Are you using Euclids algorithm to find GCD?



public class GCDNO1 {



public static int GCD(int a, int b)

{



if (a % b == 0) return b;

else if (a % b !=0)

return GCD(b, a % b);

else

return GCD(a-1, GCD(a,b-1)); //check this line. I have corrected only compilation errors.

}



public static void main(String[] args) {



System.out.println("GCD(10,70)= " + GCD(10, 70));



}

}
Jimmy S
2012-04-04 11:03:32 UTC
public static int GCD(int a, int b)

{

if (a % b == 0)

return b;

else

return GCD(a, b-1);

}



//You'll also want to provide values for a and b first in main, example

int a = Integer.parseInt(args[0]); //from command line

int b = Integer.parseInt(args[1]);

System.out.println("GCD(a,b)= " + GCD(a,b)); //or you can just replace a and b with anything
anonymous
2012-04-04 10:42:03 UTC
You need to actually use the mod symbol (%) instead of typing mod! Change the lines that say stuff like "a mod b" to "a % b". Also, your else clause does nothing. You should replace the else if with an else and get rid of the original else because it will never be executed: a % b either equals 0 or it doesn't, there's no other option. You didn't say what errors you are having, so if there are others, you should add more details. I hope this helps.
anonymous
2012-04-04 10:51:43 UTC
public class GCDNO1 {



public static int GCD(int a, int b)

{



if (a % b == 0)

{

return b;

}

else if (a % b !=0)

{

return GCD(b, a % b);

}

else

{

return GCD((a-1), (GCD(a, b-1)));

}

}



public static void main(String[] args)

{

int a = 30;

int b = 5;

System.out.println("GCD(a,b)= " + GCD(a, b));

}

}
galt_57
2012-04-04 10:49:01 UTC
a mod b is a % b in Java.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...