简体   繁体   English

数字 600851475143(Java)的最大质因数是多少? 我的错误可能是什么?

[英]What is the largest prime factor of the number 600851475143(Java)? What could be my mistake?

The code works just fine for the int data type, but 600851475143 seems to be too big of a number.该代码适用于 int 数据类型,但 600851475143 似乎太大了。 How can I make it work?我怎样才能让它工作? It just keeps running and never gives me an answer.它只是继续运行,从不给我答案。

public class Main {
    public static void main(String[] args) {
       long a = 600851475143L;
        boolean prime = false;
        long big = 0L;
        for (long i = 1L; i < a; i++){
            if (a % i == 0){
                for (int j = 2; j < i/(float)2; j++){
                    if (i % j == 0){
                        prime = true;
                        break;
                    }
                }
                if(!prime){
                    big = i;
                }
            }
        }
        System.out.println(big);
    }
}

You need to use a long also for j .您还需要对j使用long

Your variable naming is also a bit misleading: prime is true when the number is not a prime...您的变量命名也有点误导:当数字不是素数时, prime为真......

Your code has a lot of problems.你的代码有很多问题。 My first advice would be to write clean and concise code with well-named variables.我的第一个建议是使用命名变量编写干净简洁的代码。 Secondly, analyze the runtime complexity of your program even if it works fast for large inputs.其次,分析程序的运行时复杂性,即使它对大量输入运行很快。 The fact that you run an inner loop inside if(a % i == 0) condition, makes your program extremely inefficient.您在if(a % i == 0)条件内运行内部循环的事实使您的程序效率极低。

Here I provide a refactored version of your code with runtime complexity and good variable names in mind:在这里,我提供了代码的重构版本,其中考虑了运行时复杂性和良好的变量名称:

  public static void main(String[] args) {
    System.out.println(largestPrimeFactorOf(600851475143L));
  }

  public static long largestPrimeFactorOf(long input)
  {
    List<Long> factors = new ArrayList<>();
    // You start from 2, as 1 is not a prime number and also using 1 will cause an infinite loop
    for (long i = 2L; i < input; i++) {
      if (input % i == 0) {
        factors.add(i);
        while (input % i == 0) {
          input /= i;
        }
      }
    }

    // As we always add a bigger number to the factor list, the last element is the greatest factor.
    return factors.get(factors.size() - 1);
  }

Denote that this program will still be slow when the input is a large prime number, eg 100000000019. To handle such cases efficiently, it's better to use an efficient primality test algorithm.表示当输入是一个大素数时,这个程序仍然会很慢,例如 100000000019。为了有效地处理这种情况,最好使用有效的素数测试算法。 You can search the web for that.您可以搜索 web。 https://en.wikipedia.org/wiki/Primality_test https://en.wikipedia.org/wiki/Primality_test

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

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