使用 Java 查找 Long 数的素因数
public class prime
{
public static void main(String[] args)
{
long thing = 600851475143L;
for(long i = 300425737571L ; i == 0 ; i-- ){
if (thing % i == 0)
{
long answer = i;
System.out.println(answer);
break;
}
}
}
}
这是我目前拥有的代码,但是我已经在 DrJava 中运行了几分钟,但没有返回任何结果。我猜我的代码大约有一百万种可以优化的方法;有人能给我一些建议吗?
今天尝试解决一些编程问题,而这个问题给我带来了一些麻烦。
多谢 :)
public class prime
{
public static void main(String[] args)
{
long thing = 600851475143L;
for(long i = 300425737571L ; i == 0 ; i-- ){
if (thing % i == 0)
{
long answer = i;
System.out.println(answer);
break;
}
}
}
}
This is the code I currently have, however I have been running it in DrJava for a few minutes and it has returned no results. I'm guessing there are roughly a million ways my code can be optimised though ; would anyone be able to give me some tips ?
Trying to work through a few programming problems today and this one is causing me some trouble.
Thanks a lot :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不过,您只需要迭代到 sqrt(thing) 即可。
一般来说,从 2 开始迭代会更快,因为一半的数字的因数为 2(1/3 的因数为 3 等)。
您也只破坏第一个因数,因此会错过任何其他因数
You only need iterate down to sqrt(thing), though.
And in general it's going to be quicker to iterate starting from 2, since half the numbers will have a factor of two (and 1/3 a factor of 3 etc.
You're also breaking only on the first factor so will miss any others
为了计算不是很大的值的质因数,生成达到“事物”的平方根的质数,然后一一尝试会更有效。
素数生成可以通过以下方式完成:
For calculating prime factors on not extremely big values, it would be much more efficient to generate primes up to square root of "thing", and then try them one by one.
Primes generation may be done:
不,它会立即终止,因为
不会在第一次迭代中保留。
您可能想写这样的内容:
然而,这种简单的因式分解方法效率极低。由于
600851475143
的因式分解为71 * 839 * 1471 * 6857
,因此您必须从 300425737571 迭代到 6857,并每次都进行取模。有很多但并不复杂的方法可以立即解决长整数因式分解问题。No, it's terminating right away, since
will not hold on the first iteration.
You probably wanted to write something like this:
This naive factorization method however is extremely inefficient. Since the factorization of
600851475143
is71 * 839 * 1471 * 6857
you would have to iterate from 300425737571 to 6857 and do a modulo each time. There are many, not that complicated methods that would solve factorization for longs in an instant.