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

4 Answers

0 votes
public class CalculateGCDOfTwoNumbers_Java {
    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
edited Sep 4, 2024 by avibootz
0 votes
public class CalculateGCDOfTwoNumbers_Java {
    public static int GCD(int a, int b) {
        int gcd = 0;
        
        int i = a < b ? a : b;
    
        for (;i <= a && i <= b; i--) {
            if (a % i == 0 && b % i == 0) {
                gcd = i;
                break;
            }
        }
        
        return gcd;
    }
    
    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));
    }
}

 
      
/*
run:
     
The GCD (greatest common divisor) of 12 and 20 is: 4
      
*/

 



answered May 29, 2017 by avibootz
edited Sep 4, 2024 by avibootz
0 votes
public class MyClass {
    
    static int gcd(int a, int b) {
        return b == 0 ? a : gcd(b, a % b);
    }
    
    public static void main(String args[]) {
        int a = 12, b = 20, gcd = 0;
       
        System.out.format("The GCD of %d and %d is: %d\n", a, b, gcd(a, b));
    }
}



     
/*
run:
    
The GCD of 12 and 20 is: 4
     
*/

 



answered May 29, 2017 by avibootz
edited Apr 27, 2023 by avibootz
0 votes
public class MyClass {
    
    static int gcd(int a, int b) {
        int gcd = 0;
        
        for (int i = 1; i <= a && i <= b; i++) {
            if (a % i == 0 && b % i == 0)
                gcd = i;
        }
        
        return gcd;
    }
    
    public static void main(String args[]) {
        int a = 12, b = 20;
       
        System.out.format("The GCD of %d and %d is: %d\n", a, b, gcd(a, b));
    }
}



     
/*
run:
    
The GCD of 12 and 20 is: 4
     
*/

 



answered Apr 27, 2023 by avibootz
...