java common factor of two numbers code example
Example 1: a recursive function that calculates the greatest common divisor from user's input in java
public class GCDExample {
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter first number to find GCD");
int number1 = scanner.nextInt();
System.out.println("Please enter second number to find GCD");
int number2 = scanner.nextInt();
System.out.println("GCD of two numbers " + number1 +" and "
+ number2 +" is :" + findGCD(number1,number2));
}
private static int findGCD(int number1, int number2) {
if(number2 == 0){
return number1;
}
return findGCD(number2, number1%number2);
}
}
Output:
Please enter first number to find GCD
54
Please enter second number to find GCD
24
GCD of two numbers 54 and 24 is :6
Example 2: a recursive function that calculates the greatest common divisor from user's input in java
public int gcd(int a, int b) {
if (b==0) return a;
return gcd(b,a%b);
}