Java Program on GCD of Two Numbers
- Categories Java
Write a Program in Java to print GCD of two numbers.
The GCD (Greatest Common Divisor) of two numbers is the largest positive integer number that divides both the numbers without leaving any remainder.
For example. GCD of 30 and 45 is 15.
import java.util.Scanner; public class GCD { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int num1, num2, gcd = 1; System.out.println("Enter first number:"); num1= sc.nextInt(); System.out.println("Enter second number:"); num2= sc.nextInt(); for(int i = 1; i <= num1 && i <= num2; i++) { if(num1%i==0 && num2%i==0) gcd = i; } System.out.printf("GCD of "+num1+" and "+num2+" is= "+gcd); } }
You may also like
Single Linked List Programs in Java
28 August, 2021
Implementing Stack using Array in Java
28 August, 2021
Constructor Programs
3 July, 2021