Write a program to find the greatest common divisor of two numbers.
Java Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Create a Scanner object System.out.print("Enter a Number 1:"); int n1 = scanner.nextInt(); System.out.print("Enter a Number 2:"); int n2 = scanner.nextInt(); int gcd = 1; for(int i = 1; i <= n1 && i <= n2; ++i) { // Checks if i is factor of both integers if(n1 % i==0 && n2 % i==0) gcd = i; } System.out.printf("G.C.D of %d and %d is %d \n", n1, n2, gcd); } |
Output: