求最大公约数,用java实现

设输人的两个整数为nl和n2。已知1是一个公约数,但是它可能不是最大公约数。所以,可以检测k(k=2,3,4…)是否为nl和n2的最大公约数,直到k大于n1或n2。公约数存储在名为gcd的变量中,gcd的初值设为1。当找到一个新的公约数时,它就成为新的gcd。当检査完在2到n1或n2“之间所有可能的公约数后,变量gcd的值就是最大公约数。
代码:

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);
    }
}

结果显示:

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

上一篇:RabbitMQ Step by step(一) 安装


下一篇:CentOS8安装java JDK