Write a java program to find GCD of two numbers

In this program, we have covered different logic in java programs to find GCD of two numbers.

We have initialized two numbers n1=11 and n2=102. After that, we have used a for loop that runs from 1 to the smallest of both numbers. It executes until the condition i<=n1 && i<=n2 returns true. Inside the for loop, we have also used if statement that tests the condition (n1%i== && n2%i==0) and returns true if both conditions are satisfied. At last, we have stored the value of i in the variable gcd and print the same gcd variable.

  • Program:

class Main {
  public static void main(String[] args) {
    
    int n1 = 11, n2 = 102; // find GCD between n1 and n2
   
    int gcd = 1; // initially set to gcd

    for (int i = 1; i <= n1 && i <= n2; ++i) {
   
      if (n1 % i == 0 && n2 % i == 0) // check if i perfectly divides both n1 and n2
        gcd = i;
    }

    System.out.println("GCD of " + n1 +" and " + n2 + " is " + gcd);
  }
}

  • Output:

GCD of 11 and 102 is 1

0 comments