Java Program to find GCD of 2 Numbers




Java Program to find gcd of 2 numbers
  • What is gcd ?
"In mathematics, the greatest common divisor (gcd), also known as the greatest common denominator, greatest common factor (gcf), or highest common factor (hcf), of two or more non-zero integers, is the largest positive integer that divides the numbers without a remainder. For example, the GCD of 8 and 12 is 4".

Using if conditional statement and for loop.
Read 2 numbers from user and print the gcd of these number.


Code
   //Program to find gcd of 2 numbers
import java.util.Scanner;
public class gcd {
	public static void main(String args[]) {
		int i,gcdV=0;
		Scanner sc =new Scanner(System.in);
		System.out.print("Enter first number :");
		int num1 = sc.nextInt();
		System.out.print("Enter Second number :");
		int num2 = sc.nextInt();
		for(i=1; i<num1 && i<num2;i++) {
			if(num1%i==0 && num2%i ==0) {
				gcdV = i;
								
			}
		}
		System.out.println("GCD of "+num1 +" and "+ num2 +" is "+ gcdV);
	}

}

     
     

Output
Enter first number :8
Enter Second number :12
GCD of 8 and 12 is 4

     
     

Post a Comment

0 Comments