简体   繁体   English

使用Java查找长数的素数

[英]Finding the prime factor of a Long number using Java

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. 这是我目前拥有的代码,但是我已经在DrJava中运行了几分钟,它没有返回任何结果。 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 :) 非常感谢 :)

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: 素数生成可以完成:

You only need iterate down to sqrt(thing), though. 不过,您只需要迭代到sqrt(thing)。

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. 通常,从2开始迭代将更快,因为一半的数字将具有2的因子(而1/3的因子将是3的因子,依此类推)。

You're also breaking only on the first factor so will miss any others 您也只在第一个因素上挣扎,因此会错过任何其他因素

 long thing = 600851475143L;
 for(long i = 0; i < 300425737571L ; i++ ){
     if (i * i > thing) {
       break;
     }
     if (thing % i == 0) {
       long answer = i;
       System.out.println(answer);
       break;
     }
 }
  • more sophisticated methods are available as aioobe says 如aioobe所说,可以使用更复杂的方法

No, it's terminating right away, since 不,它马上终止,因为

i == 0

will not hold on the first iteration. 不会保留第一次迭代。

You probably wanted to write something like this: 您可能想写这样的东西:

public class Test {
    public static void main(String[] args) {
        long thing = 600851475143L;
        for (long i = 16857 /* 300425737571L */; i > 0; i--) {
            if (thing % i == 0) {
                long answer = i;

                // Print the largest prime factor, then break loop (and quit)
                System.out.println(answer);
                break;
            }
        }
    }
}

This naive factorization method however is extremely inefficient. 但是,这种幼稚的分解方法效率极低。 Since the factorization of 600851475143 is 71 * 839 * 1471 * 6857 you would have to iterate from 300425737571 to 6857 and do a modulo each time. 由于600851475143的因式分解为71 * 839 * 1471 * 6857您必须从300425737571迭代到6857并每次取模。 There are many, not that complicated methods that would solve factorization for longs in an instant. 有许多复杂的方法可以立即解决因式分解问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM