What is the approach to find the GCD (Greatest Common Divider) with three numbers?
The following code shows the approach with 2 numbers, which uses an elementary version of Euclids algorithm (since input is positive) to calculated the GCD.
public class GCD {
public static void main(String[] args) {
int age1 = 10;
int age2 = 15;
int multiple1OfGCD = age1;
int multiple2OfGCD = age2;
while (multiple1OfGCD != multiple2OfGCD ) {
if (multiple1OfGCD > multiple2OfGCD) {
multiple1OfGCD -= multiple2OfGCD;
}
else {
multiple2OfGCD -= multiple1OfGCD;
}
}
System.out.println("The GCD of " + age1 + " and " + age2 + " is " + multiple1OfGCD);
int noOfPortions1 = age1 / multiple1OfGCD;
int noOfPortions2 = age2 / multiple1OfGCD;
System.out.println("So the cake should be divided into "
+ (noOfPortions1 + noOfPortions2));
System.out.println("The " + age1 + " year old gets " + noOfPortions1
+ " and the " + age2 + " year old gets " + noOfPortions2);
}
}
I want the output to look like in picture below:
.
See Question&Answers more detail:os