Prime Factorization Program in Java

后端 未结 12 1604
自闭症患者
自闭症患者 2021-01-03 11:11

I am working on a prime factorization program implemented in Java. The goal is to find the largest prime factor of 600851475143 (Project Euler problem 3). I think I have m

相关标签:
12条回答
  • 2021-01-03 12:01
    public class Prime
    {
     int i;   
    
     public Prime( )
     {
        i = 2;
     }
    
     public boolean isPrime( int test ) 
     {
        int k;
    
        if( test < 2 )
            return false;
        else if( test == 2 )  
            return true;
        else if( ( test > 2 ) && ( test % 2 == 0 ) )
            return false;
        else
        {
            for( k = 3; k < ( test/2 ); k += 2 )
            {
                if( test % k == 0 ) 
                    return false;
            }
    
        }
    
        return true;
    
     }
    
     public void primeFactors( int factorize )
     {
        if( isPrime( factorize ) )
        {
            System.out.println( factorize );
            i = 2;
        }
        else
        {
            if( isPrime( i ) && ( factorize % i == 0 ) )
            {
                System.out.print( i+", " );
                primeFactors( factorize / i );
            }
            else
            {
                i++;
                primeFactors( factorize );
            }
       }
    
       public static void main( String[ ] args )
       {
           Prime p = new Prime( );
    
           p.primeFactors( 649 );
           p.primeFactors( 144 );
           p.primeFactors( 1001 );
       }
    }
    
    0 讨论(0)
  • 2021-01-03 12:05
        private static boolean isPrime(int k) throws IllegalArgumentException
         {
            int j;
    
            if (k < 2) throw new IllegalArgumentException("All prime numbers are greater than 1.");
            else {
                for (j = 2; j < k; j++) {
                    if (k % j == 0) return false;
                }
            }
    
            return true;
        }
    
        public static void primeFactorsOf(int n) {
            boolean found = false;
    
            if (isPrime(n) == true) System.out.print(n + " ");
            else {
                int i = 2;
                while (found == false) {
                    if ((n % i == 0) && (isPrime(i))) {
                        System.out.print(i + ", ");
                        found = true;
                    } else i++;
                }
                primeFactorsOf(n / i);
            }
        }
    
    0 讨论(0)
  • 2021-01-03 12:06

    I think you're confused because there is no iff [if-and-only-if] operator.

    Going to the square root of the integer in question is a good shortcut. All that remains is checking if the number within that loop divides evenly. That's simply [big number] % i == 0. There is no reason for your Prime function.

    Since you are looking for the largest divisor, another trick would be to start from the highest integer less than the square root and go i--.

    Like others have said, ultimately, this is brutally slow.

    0 讨论(0)
  • 2021-01-03 12:08

    Why make it so complicated? You don't need do anything like isPrime(). Divide it's least divisor(prime) and do the loop from this prime. Here is my simple code :

    public class PrimeFactor {
    
        public static int largestPrimeFactor(long number) {
            int i;
    
            for (i = 2; i <= number; i++) {
                if (number % i == 0) {
                    number /= i;
                    i--;
                }
            }
    
            return i;
        }
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            System.out.println(largestPrimeFactor(13195));
            System.out.println(largestPrimeFactor(600851475143L));
        }
    }
    
    0 讨论(0)
  • 2021-01-03 12:09

    For those answers which use a method isPrime(int) : boolean, there is a faster algorithm than the one previously implemented (which is something like)

    private static boolean isPrime(long n) { //when n >= 2
        for (int k = 2; k < n; k++)
            if (n % k == 0) return false;
    
        return true;
    }
    

    and it is this:

    private static boolean isPrime(long n) { //when n >= 2
        if (n == 2 || n == 3) return true;
    
        if (n % 2  == 0 || n % 3 == 0) return false;
    
        for (int k = 1; k <= (Math.floor(Math.sqrt(n)) + 1) / 6; k++)
            if (n % (6 * k + 1) == 0 || n % (6 * k - 1) == 0) return false;
    
        return true;
    }
    

    I made this algorithm using two facts:

    1. We only need to check for n % k == 0 up to k <= Math.sqrt(n). This is true because for anything higher, factors merely "flip" ex. consider the case n = 15, where 3 * 5 = 5 * 3, and 5 > Math.sqrt(15). There is no need for this overlap of checking both 15 % 3 == 0 and 15 % 5 == 0, when we could just check one of these expressions.
    2. All primes (excluding 2 and 3) can be expressed in the form (6 * k) + 1 or (6 * k) - 1, because any positive integer can be expressed in the form (6 * k) + n, where n = -1, 0, 1, 2, 3, or 4 and k is an integer <= 0, and the cases where n = 0, 2, 3, and 4 are all reducible.

    Therefore, n is prime if it is not divisible by 2, 3, or some integer of the form 6k ± 1 <= Math.sqrt(n). Hence the above algorithm.

    --

    Wikipedia article on testing for primality

    --

    Edit: Thought I might as well post my full solution (*I did not use isPrime(), and my solution is nearly identical to the top answer, but I thought I should answer the actual question):

    public class Euler3 {
    
        public static void main(String[] args) {
            long[] nums = {13195, 600851475143L};
    
            for (num : nums)
                System.out.println("Largest prime factor of " + num + ": " + lpf(num));
    
        }
    
        private static lpf(long n) {
            long largestPrimeFactor = 1;
            long maxPossibleFactor = n / 2;
    
            for (long i = 2; i <= maxPossibleFactor; i++)
                if (n % i == 0) {
                    n /= i;
                    largestPrimeFactor = i;
    
                    i--;
                }
    
                return largestPrimeFactor;
    
        }
    
    }
    
    0 讨论(0)
  • 2021-01-03 12:11

    You need to do some research on algorithms for factorizing large numbers; this wikipedia page looks like a good place to start. In the first paragraph, it states:

    When the numbers are very large, no efficient integer factorization algorithm is publicly known ...

    but it does list a number of special and general purpose algorithms. You need to pick one that will work well enough to deal with 12 decimal digit numbers. These numbers are too large for the most naive approach to work, but small enough that (for example) an approach based on enumerating the prime numbers starting from 2 would work. (Hint - start with the Sieve of Erasthones)

    0 讨论(0)
提交回复
热议问题