简体   繁体   中英

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. 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 .

Your variable naming is also a bit misleading: prime is true when the number is not a 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.

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. You can search the web for that. https://en.wikipedia.org/wiki/Primality_test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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