Java USES division to find the greatest common divisor

  • 2020-04-01 03:53:38
  • OfStack

The better method is division.
For example: 49 and 91
  A          B              temp
49   %   91   =   49
91   %   49   =   42
49   %   42   =   7
42   %   7       =   0
So the greatest common divisor is 7.


public class T {
 public static void main(String[] args) {
 int gcd = gcd(91, 49);
 System.out.println(gcd);
 }

 
 public static int gcd(int a, int b) {
 while(b != 0) {
  int temp = a%b;
  a = b;
  b = temp;
 }
 return a;
 }

}


Related articles: