Welcome to collectivesolver - Programming & Software Q&A. A website you can trust. I check, compile and run every program. Contact me at: aviboots(AT)netvision.net.il
Hostgator 1 Penny

BlueHost Web Hosting

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

getflywheel wordpress hosting


Distribute your Resume to 500+ Job Boards & Recruiters


6,869 questions

9,775 answers

573 users

How to calculate the GCD (greatest common divisor) of two numbers in Java

3 Answers

0 votes
package javaapplication1;

public class JavaApplication1 {
  
    public static void main(String[] args) {
         
        int a = 12, b = 20, gcd = 0;
      
        for (int i = 1; i <= a && i <= b; i++)
        {
            if (a % i == 0 && b % i == 0)
                gcd = i;
        }
  
        System.out.format("The GCD (greatest common divisor) of %d and %d is: %d\n", a, b, gcd);
    }
}
    
/*
run:
   
The GCD (greatest common divisor) of 12 and 20 is: 4
    
*/

 




answered May 29, 2017 by avibootz
0 votes
package javaapplication1;

public class JavaApplication1 {
  
    public static void main(String[] args) {
         
        int a = 12, b = 20, gcd = 0;
      
        int i = a < b ? a : b;
  
        for (;i <= a && i <= b; i--)
        {
            if (a % i == 0 && b % i == 0)
            {
                gcd = i;
                break;
            }
        }
  
        System.out.format("The GCD (greatest common divisor) of %d and %d is: %d\n", a, b, gcd);
    }
}
    
/*
run:
   
The GCD (greatest common divisor) of 12 and 20 is: 4
    
*/

 




answered May 29, 2017 by avibootz
0 votes
package javaapplication1;

public class JavaApplication1 {
  
    public static void main(String[] args) {
         
        int a = 12, b = 20;
  
        System.out.format("The GCD (greatest common divisor) of %d and %d is: %d\n", a, b, gcd(a, b));
    }
    static int gcd(int a, int b) 
    {
        return b == 0 ? a : gcd(b, a % b);
    }
}
    
/*
run:
   
The GCD (greatest common divisor) of 12 and 20 is: 4
    
*/

 




answered May 29, 2017 by avibootz
...