The GCD
by CodeChum Admin
The greatest common divisor, also known as GCD, is the greatest number that will, without a remainder, fully divide a pair of integers.
Now, I want you to make a program that will accept two integers and with the use of loops, print out their GCD. Make good use of conditional statements as well.
Off you go!
Input
A line containing two integers separated by a space.
6·9
Output
A line containing an integer.
3
package gcd;
import java.util.Scanner;
public class GCD {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int first = scan.nextInt();
int second = scan.nextInt();
for(int i=second; i>=1; i--){
if(second % i==0 && first %i==0){
System.out.println("The GCD is: "+ i);
break;
}
}
}
}
Comments
Leave a comment