Problem:
The greatest common divisor (GCD) of two integers is the largest integer that evenly divides each of the two numbers. Write an application that reads two integers from the user and then prints their greatest common divisor. Implement this exercise using Functions.
Output:
Not needed.
Solution:
import java.util.Scanner; public class problem4 { public static void main(String[] args) { Scanner scan=new Scanner(System.in); int GCD=0,smallest; System.out.println("Enter the two numbers:"); int num1=scan.nextInt(); int num2=scan.nextInt(); if(num1<num2) smallest=num1; else smallest=num2; for(int n=smallest;n>=1;n--) { if((num1%n==0) && (num2%n==0)) { GCD=n; n=0;//to exit loop } } System.out.println("The GCD is: "+ GCD); } }
No comments :
Post a Comment