【问题标题】:How can I get largest prime factors between two numbers and store them in an array?如何获得两个数字之间的最大素数并将它们存储在数组中?
【发布时间】:2014-03-24 12:37:56
【问题描述】:

我被要求解决这个问题:

编写一个函数,将两个数字 n1n2 作为输入(使用 n2>n1) 并返回对应于的最大素因子数组 n1n2 之间的每个数字。

我的尝试如下所示,但我的代码无法正常工作。它不是从n1 迭代到n2。我怎样才能正确?

public static class A{
        static int testcase1=5;
        static int testcase2=10;

        public static void main(String args[]){
            A testInstance = new A();
            int[] result = testInstance.getLpfd(testcase1,testcase2);
            System.out.print("{");
            for (int i=0;i<result.length;i++){
                if (i>0)
                    System.out.print(",");
                System.out.print(result[i]);
            }
            System.out.println("}");
        }

        public int[] getLpfd(int n1,int n2){
            int current=0;
            int[] factors = new int[20];
            for(int j=n1;j<=n2;j++){
                for (int i = 2; i <= j; i++){
                    while(j % i == 0){
                        factors[current]=i;
                        j /= i;
                        current++;
                    }
                }
            }           
            return factors;
        }
    }
}

【问题讨论】:

  • 好吧,首先你要在 while 循环中修改你的第一个 for 循环变量 (j)。这没有帮助。

标签: java arrays prime-factoring


【解决方案1】:

将寻找因子的任务与编写最大因子的任务分开是最简单的。这是一个查找因子的函数:

function factors(n)
    f, fs := 2, []
    while f * f <= n
        while n % f == 0
            insert f at head of fs
            n := n / f
        f := f + 1
    if n > 1
        insert n at head of fs
    return fs

返回 n 的因子以降序排列,因此最大的因子在列表的头部。然后很容易积累一个范围的最大素因子列表:

function lpf(lo, hi)
    result := makeArray(0 .. hi-lo)
    for n from lo to hi
        result[n-lo] := head(factors(n))
    return result

我会让你把它翻译成 Java。

如果您的范围很大,那么埃拉托色尼筛法的变体将比计算所有这些因素要快得多。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-13
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    相关资源
    最近更新 更多