1. Introduction
Suppose the two integers to be input are nl and n2. It is known that 1 is a common divisor, but it may not be the greatest common divisor. Therefore, it can be tested whether k (k=2,3,4...) is the greatest common divisor of nl and n2, until k is greater than n1 or n2. The common divisor is stored in a variable named gcd, and the initial value of gcd is set to 1. When a new common divisor is found, it becomes the new gcd. After checking all possible common divisors between 2 and n1 or n2", the value of the variable gcd is the greatest common divisor.
2. Code
package com.zhuo.base.com.zhuo.base;
import java.util.Scanner;
public class GretestCommonDivisor {
//main方法
public static void main(String[] args) {
//创建一个Scanner
Scanner input = new Scanner(System.in);
//提示用户输入两个数字
System.out.print("Enter first integer: ");
int n1 = input.nextInt();
System.out.print("Enter second integer: ");
int n2 = input.nextInt();
int gcd = 1;
int k = 2;
while (k <= n1 && k <= n2) {
if(n1 % k == 0 && n2 % k == 0)
gcd = k;
k++;
}
System.out.println("The gretest common divisor for " + n1 + " and " + n2 +" is " + gcd);
}
}
Three. Results display
D:\Java\jdk1.8.0_281\bin\java.exe "-javaagent:D:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2020.3.2\lib\idea_rt.jar=53757:D:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\Java\jdk1.8.0_281\jre\lib\charsets.jar;D:\Java\jdk1.8.0_281\jre\lib\deploy.jar;D:\Java\jdk1.8.0_281\jre\lib\ext\access-bridge-64.jar;D:\Java\jdk1.8.0_281\jre\lib\ext\cldrdata.jar;D:\Java\jdk1.8.0_281\jre\lib\ext\dnsns.jar;D:\Java\jdk1.8.0_281\jre\lib\ext\jaccess.jar;D:\Java\jdk1.8.0_281\jre\lib\ext\jfxrt.jar;D:\Java\jdk1.8.0_281\jre\lib\ext\localedata.jar;D:\Java\jdk1.8.0_281\jre\lib\ext\nashorn.jar;D:\Java\jdk1.8.0_281\jre\lib\ext\sunec.jar;D:\Java\jdk1.8.0_281\jre\lib\ext\sunjce_provider.jar;D:\Java\jdk1.8.0_281\jre\lib\ext\sunmscapi.jar;D:\Java\jdk1.8.0_281\jre\lib\ext\sunpkcs11.jar;D:\Java\jdk1.8.0_281\jre\lib\ext\zipfs.jar;D:\Java\jdk1.8.0_281\jre\lib\javaws.jar;D:\Java\jdk1.8.0_281\jre\lib\jce.jar;D:\Java\jdk1.8.0_281\jre\lib\jfr.jar;D:\Java\jdk1.8.0_281\jre\lib\jfxswt.jar;D:\Java\jdk1.8.0_281\jre\lib\jsse.jar;D:\Java\jdk1.8.0_281\jre\lib\management-agent.jar;D:\Java\jdk1.8.0_281\jre\lib\plugin.jar;D:\Java\jdk1.8.0_281\jre\lib\resources.jar;D:\Java\jdk1.8.0_281\jre\lib\rt.jar;D:\IdeaProjects\JavaSE\out\production\Practise com.zhuo.base.com.zhuo.base.GretestCommonDivisor
Enter first integer: 125
Enter second integer: 2525
The gretest common divisor for 125 and 2525 is 25
Process finished with exit code 0