找到两个用户定义数字的最大公因数和因数对

问题描述 投票:0回答:1
public static void findGreatestCommonFactor(Scanner sc){
        System.out.println("Enter the first number:");
        int num1 =sc.nextInt();
        System.out.println("Enter the second number:");
        int num2 =sc.nextInt();
        factorPairs(num1);
        factorPairs(num2);
        int gcf = 1;
        for (int i=1; i <= num1; i++){
            if (num1 % i==0 && num2 % i==0){
                gcf=i;
            }
        }
        System.out.println("The greatest common factor (GCF) of "+ num1 +" and "+ num2 +" is "+ gcf +".");
    }
    public static void factorPairs(int n){
        System.out.print("The factor pairs of "+n+" are: {");
        for (int i =n; i<+ n; i++){
            if (n % i==0){
                System.out.print(i);
                if (i != n){
                    System.out.print(", ");
                }else{
                    System.out.print("}.\n");
                }
            }
        }
    }

我面临的问题是25的因数应该是1,5,5,25,但我的代码输出1,5,25。不知道为什么它会跳过第二个值 5。

java for-loop greatest-common-divisor
1个回答
0
投票

我面临的问题是25的因数应该是1,5,5,25,但我的代码输出1,5,25。不知道为什么它会跳过第二个值 5。

您没有找到它的原因是您只在 for 循环中递增时除以每个测试候选者

i
一次。

为什么要多次打印任何除数?仅仅因为

5
出现多次并不能使其成为附加除数。对于 625,你会显示
1, 5, 25, 125, 625
,恕我直言,这很好。我会使用术语
divisors
,因为
factors
通常指的是素数。 .

我还建议你修改你的

factorPairs
方法。假设
n > 0
,就像
1
总是整除
n
一样,
n
也会整除自己。所以只需打印
n
以及循环后的右大括号即可。

public static void factorPairs(int n) {
    System.out.print("The factor pairs of " + n + " are: {");
    for (int i = 1; i < n; i++) {
        if (n % i == 0) {
            System.out.print(i + ", ");
        }
    }
    System.out.println(n + "}");
}

另请注意以下事项:

for (int i = 1; i <= num1; i++) {
      if (num1 % i == 0 && num2 % i == 0) {
          gcf = i;
      }
}

如果

num1
远大于
num2
,则无需继续循环,因为
gcf
不能大于
num2
。因此,请考虑使用 Math.min() 来查找要在循环中使用的最小的一个。

您可能还想查看欧几里得方法来寻找最大公约数(GCD)。

© www.soinside.com 2019 - 2024. All rights reserved.