The gcd method can be iterated to obtain the gcd of a larger set of numbers.
For example:
gCd(a, b, c) = gCd( gCd(a, b), c)
and
gCd(a, b, c, d) = gCd( gCd(a, b, c), d)
so then
gCd(a, b, c, d) = gCd( gCd( gCd(a, b), c), d)
Easy, specific solution:
System.out.println("GCD is: " + gCd( gCd(a, b), c) );
However, if you'll notice, there is recursion going on. I've created a method that takes an array of integers as an input. It will work for an array of size three, or any size. Here are the methods:
/* returns gcd of two numbers: a and b */
public static int gCd(int a, int b) {
if (b == 0) {
return a;
}
return gCd(b, a%b);
}
/* returns gcf of an array of numbers */
public static int gCd(int[] numbers)
{
int result = numbers[0]; // first number
for(int i = 1; i < numbers.length; i++) {
result = gCd(result, numbers[i]); // gcf of itself and next #
}
return result;
}
So, to relate it to your code:
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("Enter third number: ");
int c = userInput.nextInt();
// you can do this
System.out.println("GCD is: " + gCd( gCd(a, b), c) );
// or you can do this
int[] numbers = {a, b, c};
int d = gCd(numbers);
System.out.println("GCD is: " + d);
Sample input/output:
Enter first number:
12
Enter second number:
18
Enter third number:
30
GCD is: 6
GCD is: 6