Using recursion and implementing Euclid's algorithm to find GCD of three numbers from user

TroutmasterJ picture TroutmasterJ · Mar 22, 2014 · Viewed 14.6k times · Source

I am wanting to ask the user to input three numbers and then have program calculate the GCD using Euclid's algorithm all the while using recursion.

My code right now implements two input numbers. I understand the approach of calculating the GCD of a and b, and calling it result d. Then using the third input (c) and d to find the GCD and essentially repeating Euclid's algorithm again; I am not sure how to implement this in code.

import java.util.Scanner;

public class RecursionDemo {

public static void main (String[] args) {

Scanner userInput = new Scanner(System.in);

     System.out.println("Enter first number: ");
     int a = userInput.nextInt();

     System.out.println("Enter second number: ");
     int b = userInput.nextInt();


     System.out.println("GCD is: " + gCd(a, b));
   }

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

     if(b == 0){
         return a;
        }
     return gCd(b, a%b);         
   }
}   

The part that is really throwing me off is using recursion to solve my problem.

So far I know I need to implement:

System.out.println("Enter third number: ");
     int c = userInput.nextInt();

d = //Not sure here

//And then modify my recursion method to find GCD.

Any help or suggestions would greatly be appreciated!

Answer

Gassa picture Gassa · Mar 22, 2014
d = gCd (a, b);
System.out.println("GCD is: " + gCd(d, c));

Note that you may call your gCd function with any two arguments, not just a and b. For better understanding and less confusion, you may want to rename its arguments, like the following:

 public static int gCd(int x, int y) {
     if(y == 0) {
         return x;
     }
     return gCd(y, x%y);
 }

So, first you call it with x = a and y = b to find GCD of a and b. Store the result into new variable d. After that, you call it again with x = d which is in turn GCD of a and b, and y = c. Thus you get the GCD of all the three numbers.