Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

java - whats the approach to calculate GCD for 3 numbers

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:

Want the output to look like this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Hope It will help

 public static void main (String[] args)
{
 int a,b,c;
 a=10;
 b=15;
 c=20;
 int d= gcd(a,b,c);
 System.out.println("The GCD of "+a+", "+b+" and "+c+ " is "+d);
 int cake=a/d+b/d+c/d;
 System.out.println("So the cake is divided into "+ cake);
 System.out.println("The "+a+ " Years old get "+a/d );
 System.out.println("The "+b+ " Years old get "+b/d );
 System.out.println("The "+c+ " Years old get "+c/d );
}

public static int gcd(int a, int b, int c){
 return calculateGcd(calculateGcd(a, b), c);
}

public static int calculateGcd(int a, int b) {
    if (a == 0) return b;
    if (b == 0) return a;
    if (a > b) return calculateGcd(b, a % b);
    return calculateGcd(a, b % a);
 }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...