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

  • Visit:

Java program to print an Integer Here
Java program to add two integers Here
Java program to find ASCII value of a character Here
Java program to compute quotient and remainder Here
Java program to swap two numbers Here
Java program to check whether a given number is even or odd Here
Java program to check whether an alphabet is vowel or consonant Here 
Java program to find the largest among three numbers Here
Java program to find all roots of a quadratic equation Here
Java program to check leap year Here
Write a java program to multiply two floating point numbers Here
Java program to check whether a number is positive or negative Here
Java program to check whether a character is alphabet or not Here
Java program to calculate the sum of natural numbers Here
Java program to find factorial of a number Here
Java program to generate multiplication table Here
Write a java program to display Fibonacci series Here

0 comments