Project Euler #3 takes forever in Java

后端 未结 9 837
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-04 03:01

Problem #3 on Project Euler is:

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 60085147514

9条回答
  •  孤街浪徒
    2020-12-04 03:21

    You could just prime factorize the number and then the largest prime factor would be the answer:

    import java.util.ArrayList;
    import java.util.Collections;
    
    public class PrimeFactorization {
    
        /* returns true if parameter n is a prime number, 
             false if composite or neither */
        public static boolean isPrime(long n) {
            if (n < 2) return false;
            else if (n == 2) return true;
            for (int i = 2; i < Math.pow(n, 0.5) + 1; i++)
                if (n % i == 0)
                    return false;
            return true;
        }
    
        /* returns smallest factor of parameter n */
        public static long findSmallestFactor(long n) {
            int factor = 2; // start at lowest possible factor
            while (n % factor != 0) { // go until factor is a factor
                factor++; // test the next factor
            }
            return factor;
        }
    
        /* reduces the parameter n into a product of only prime numbers
           and returns a list of those prime number factors */
        public static ArrayList primeFactorization(long n) {
    
            ArrayList primes = new ArrayList();
              // list of prime factors in the prime factorization
            long largestFactor = n / findSmallestFactor(n);    
    
            long i = 2;
            while (i <= largestFactor) { 
              // for all possible prime factors 
              // (2 - largest factor of the number being reduced)
    
                if (isPrime(i) && n % i == 0) { 
                    // if this value is prime and the number is divisible by it
    
                    primes.add(i); // add that prime factor to the list
                    n /= i; // divide out that prime factor from the number 
                            // to start reducing the new number
                    largestFactor /= i; // divide out that prime factor 
                           // from the largest factor to get the largest 
                           // factor of the new number
                    i = 2; // reset the prime factor test
                } else {
                    i++; // increment the factor test
                }
            }
    
            primes.add(n); // add the last prime number that could not be factored
            Collections.sort(primes);
            return primes;
        }
    }
    

    And then call it like this:

    ArrayList primes = PrimeFactorization.primeFactorization(600851475143L);
    System.out.println(primes.get(primes.size() - 1));
    

    The entire thing takes only a few milliseconds.

提交回复
热议问题