Methods

PHOTO EMBED

Sat Oct 14 2023 16:59:59 GMT+0000 (Coordinated Universal Time)

Saved by @Mohamedshariif #java

Write a method that takes 2 integers as input parameters, computes and returns their greatest common divisor (GCD).
The greatest common divisor of a set of whole numbers is the largest integer which divides them all.
Example: The greatest common divisor of 12 and 15. 
Divisors of 12: 1, 2, 3, 4, 6, 12
Divisors of 15: 1, 3, 5, 15
Common divisors: 1, 3
Greatest common divisor is 3
gcd(12,15)=3



public static void main(String[] args) {
		
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter first integer:");
		int n1 = scanner.nextInt();
		
		System.out.println("Enter secon d integer:");
		int n2 = scanner.nextInt();
		
		System.out.println("The greatest common divisor for " + n1 + " and " + n2 + " is " + gcd(n1,n2));
	}
	
	public static int gcd (int n1, int n2) {
		int gcd = 1;
		int k = 1;
		while(k <= n1 && k <= n2) {
			if(n1 % k ==0 && n2 % k ==0)
				gcd = k;
			k++;
		}
		return gcd;
	}
	
}
content_copyCOPY