In Java, Find GCD Of Array Of Integers Given By User

import java.util.Scanner;

class CalcGcd {
 
  public static void main(String[] args) {

      Scanner stdin = new Scanner(System.in);

      System.out.print("Enter 5 numbers: ");

      System.out.println("GCD: " + gcd(
        stdin.nextInt(),
        stdin.nextInt(),
        stdin.nextInt(),
        stdin.nextInt(),
        stdin.nextInt()
      ));
  }

  public static int gcd(int... numbers){
    int result = numbers[0];
    for(int i=1; i<numbers.length; i++){
      result = findGCD(numbers[i], result);
    }
    return result;
  }

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

}
Download

Comments

Popular posts from this blog