查找两个用户定义数字的最大公因数和因数对。 JAVA代码

问题描述 投票: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
投票

"The problem I am facing is the factors of 25 should be 1,5,5,25 but my code is outputting 1,5,25. not sure why it is skipping the second value of 5."

您没有找到它的原因是您只除以每个测试候选者

i
一次。

为什么要打印它?首先,我会使用术语除数,因为因子通常指的是素数。并且仅仅因为

5
出现多次并不能使其成为附加除数。

我还建议你修改你的方法。假设

n > 0
,就像 1 总是整除
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 + "}");
}
© www.soinside.com 2019 - 2024. All rights reserved.