java中的递归素因数算法
我正在尝试在java中实现一个简单的算法,用于查找参数传递的整数的所有素数因子:
private static ArrayList<Integer> lstPrime= new ArrayList<Integer>();
public static ArrayList primeFactors(int n) {
if (isPrime(n))
{
lstPrime.add(n);
}
for (int i=2; i<=(Math.sqrt(n)); i++)
{
if (n % i == 0)
{
lstPrime.addAll(primeFactors(n/i));
return lstPrime;
}
}
return lstPrime;
}
有趣的是,如果我将81作为n传递,结果将是:3,3,3,3,3,3 , 3, 3 而它应该是: 3, 3, 3, 3 (3^4=81)
I am trying to implement a simple algorithm in java for finding all prime number factors of an integer passed by parameter:
private static ArrayList<Integer> lstPrime= new ArrayList<Integer>();
public static ArrayList primeFactors(int n) {
if (isPrime(n))
{
lstPrime.add(n);
}
for (int i=2; i<=(Math.sqrt(n)); i++)
{
if (n % i == 0)
{
lstPrime.addAll(primeFactors(n/i));
return lstPrime;
}
}
return lstPrime;
}
Funny thing is that if I pass 81 as n, the result will be : 3, 3, 3, 3, 3, 3, 3, 3 while it SHOULD be : 3, 3, 3, 3 (3^4=81)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
也许有点复杂,但到目前为止它可以工作,并且它使用的可能是我在 Java 中能找到的最快(也是最小)的素数生成器。
首先,我们得到了素数生成器,需要测试一个值是否是素数。我们使用生成器(这个生成器比简单方法快 10 倍),因此我们使用缓存列表:
然后我们有两个方法来实际获取 n 的质因数列表:
最后,我们的测试用例:
例如,上面的代码将产生:
并且更改
n = 81
将产生所需的输出Perhaps a little more complex, but it works so far, and it uses probably the fastest (and smallest) prime number generator I could find in Java.
First, we got the prime number generator, needed to test if a value is prime. We use a generator (this one is 10x faster than the naïve method) so we use a cached list :
Then we have the two methods needed to actually get the list of prime factor for
n
:And finally, our test case :
For example, this code above will produce :
And changing
n = 81
will produce the desired output of问题是你的递归实现。使用这个:
the problem is your recursive implementation. use this:
好的!我想我已经解决了我的问题,除了 ArrayList 是在递归函数之外声明的这一事实。我无法想象处理列表的任何其他方式,因为由于这是一个递归函数,如果在函数内部声明列表,则每次发生递归时都会一次又一次地实例化它。这是我到目前为止所得到的,请随意批评:
例如,此代码将为
primeFactors(81)
和生成:
代表3,3,3,3
>5,3,2,2primeFactors(60)
等等...OK! I think I have solved my problem, except for the fact that the ArrayList is declared outside the recursive function. I cannot imagine any other way of treating the list because since this is a recursive function, if the list would be declared inside the function, it would be instantiated again and again each time recursion occurs. Here is what I have so far, feel free to criticize:
For example, this code will produce:
3,3,3,3
forprimeFactors(81)
and5,3,2,2
forprimeFactors(60)
and so on...编辑:
存在设计缺陷。为什么一定要归还清单。它是在函数体外部定义的,并且会针对找到的每个因素进行更新。因此,无需退货。
Edit:
There is a design flaw. Why do you have to return the list. It's defined outside the function body and would get updated for each factor found. Therefore, no need to return it.
我的 Java 很生锈,所以你必须自己添加数组/列表/向量,但这似乎比迄今为止所有其他解决方案更简单。
My Java is rusty so you'll have to add arrays/lists/vectors yourself, but this seems simpler than all the other solutions so far.