Recursion in Java
Write a recursive method that will find the greatest common divisor of two numbers. Use %.
Example of the math:
Finding GCD for 14 and 48: 14 / 48 = 3 42 ----- 6 Remainder
Remainder is not yet zero, so we will now divide 14 by 6 6 / 14 = 2 12 ----- 2 Remainder Remainder is not yet zero, so we will now divide 6 by 2 2 / 6 = 3 answer 6 ---- 0 Remainder Remainder is 0 so, we stop here To Do:
//Java Code
public class GCD {
public static void main(String[] args)
{
System.out.println(findGCD(14,48));
}
/**
* find the gcd as
* if a= 14 and b=48
* a%b = 14%48 = 6
* and we call the recursive function as
* findGCD(b,a%b)
* so now a = 48 and b = 14
* In next recursive call
* a= 14 and b= 6
* In next recursive call
* a = 6 and b =2
* in next step since b=0
* so it returns a = 2
* @param a
* @param b
* @return gcd of a,b
*/
public static int findGCD(int a, int b)
{
if(b==0)
return a;
else {
return findGCD(b, a % b);
}
}
}
//Output
//If you need any help regarding this solution.... please leave a comment.. thanks
Get Answers For Free
Most questions answered within 1 hours.