Largest prime factor program takes aaaages - Java

扶醉桌前 提交于 2019-11-30 08:50:27

问题


So this is problem 3 from project Euler. For those who don't know, I have to find out the largest prime factor of 600851475143. I have the below code:

import java.lang.Math;
// 600851475143
public class LargestPrimeFactor {
    public static void main(String[] stuff) {
        long num = getLong("What number do you want to analyse? ");
        long[] primes = primeGenerator(num);
        long result = 0;
        for(int i = 0; i < primes.length; i++) {
            boolean modulo2 = num % primes[i] == 0;
            if(modulo2) {
                result = primes[i];
            }
        }
        System.out.println(result);
    }
    public static long[] primeGenerator(long limit) {
        int aindex = 0;
        long[] ps = new long[primeCount(limit)];
        for(long i = 2; i < limit + 1; i++) {
            if(primeCheck(i)) {
                ps[aindex] = i;
                aindex++;
            }
        }
        return ps;
    }

    public static boolean primeCheck(long num) {
        boolean r = false;
        if(num == 2 || num == 3) {
            return true;
        }
        else if(num == 1) {
            return false;
        }
        for(long i = 2; i < Math.sqrt(num); i++) {
            boolean modulo = num % i == 0;
            if(modulo) {
                r = false;
                break;
            }
            else if(Math.sqrt(num) < i + 1 && !modulo) {
                r = true;
                break;
            }
        }
        return r;
    }
    public static int primeCount(long limit) {
        int count = 0;
        if(limit == 1 || limit == 2) {
            return 0;
        }
        for(long i = 2; i <= limit; i++) {
            if(primeCheck(i)) {
                count++;
            }
        }
        return count;
    }
public static long getLong(String prompt) {
    System.out.print(prompt + " ");
    long mrlong = input.nextLong();
    input.nextLine();
    return mrlong;
}
}

But when I test the program with something (a lot) smaller than 600851475143, like 100000000, then the program takes its time - in fact, 100000000 has taken 20 minutes so far and is still going. I've obviously got the wrong approach here (and yes, the program does work, I tried it out with smaller numbers). Can anyone suggest a less exhaustive way?


回答1:


try this ..

public class LargestPrimeFactor{
public static int largestPrimeFactor(long number) {
    int i;
    for (i = 2; i <= number; i++) {
        if (number % i == 0) {
            number /= i;
            i--;
        }
    }
    return i;
}

/*  change according to ur requirement. 
public static long getLong(String prompt) {
    System.out.print(prompt + " ");
    long mrlong = input.nextLong();
    input.nextLine();
    return mrlong;
}
 */

public static void main(String[] args) {
    //long num = getLong("What number do you want to analyse? ");
    System.out.println(largestPrimeFactor(600851475143l));
}
}



回答2:


public static void main(String[] args) {

    long number = 600851475143L;

    long highestPrime = -1;
    for (long i = 2; i <= number; ++i) {
        if (number % i == 0) {
            highestPrime = i;
            number /= i;
            --i;
        }
    }

    System.out.println(highestPrime);
}



回答3:


public class LargestPrimeFactor {

public static boolean isPrime(long num){
    int count = 0;
    for(long i = 1; i<=num/2 ; i++){
        if(num % i==0){
            count++;
        }
    }
    if(count==1){
        return true;
    }
    return false;
}

public static String largestPrimeFactor(long num){
    String factor = "none";
    for(long i = 2; i<= num/2 ; i++){
        if(num % i==0 && isPrime(i)){
           factor = Long.toString(i); 
        }
    }
    return factor;     
}
public static void main(String[] args) {
    System.out.println(largestPrimeFactor(13195));
}

}




回答4:


I have done several dozen of the challenges on Project Euler. Some of the questions can be solved with brute force (they recommend not to do this) but others require "out of the box" thinking. You cannot solve that by problem with brute force.

There is lots of help on the web to lead you in the right direction, for example: http://thetaoishere.blogspot.com.au/2008/05/largest-prime-factor-of-number.html




回答5:


The number of prime factors a number can have is always less than sqrt of that number so that there is no need to iterate through the number n to find its largest prime factor.

See this code.

    public class LargestPrimeFactor {
        public static void main(String[] args) {

            Scanner sc=new Scanner(System.in);
            long num=sc.nextLong();

            if(num>0 && num<=2)
            {
                System.out.println("largest prime is:-" + num);
                System.exit(0);
            }

            int i=((Double)Math.sqrt(num)).intValue();
            int j=3;
            int x=0;

            //used for looping through the j value which can also be a prime. for e.g in case of 100 we might get 9 as a divisor. we need to make sure divisor is also a prime number.
            int z=0;
//same function as j but for divisor
            int y=3;
            int max=2;
//divisor is divisible
            boolean flag=false;
//we found prime factors
            boolean found=false;

            while(x<=i)
            {
                y=3;
                flag=false;

                if(num % j ==0)
                {
                    if(j>max)
                    {
                        for(z=0;z<Math.sqrt(j);z++)
                        {
                            if(j!=y && j % y==0)
                            {
                                flag=true;
                            }
                            y+=2;
                        }
                        if(!flag)
                        {
                            found=true;
                            max=j;
                        }
                    }
                }
                j+=2;
                x++;
            }
            if(found){
                System.out.println("The maximum prime is :- " + max);
            }
            else
            {
                System.out.println("The maximum prime is :- " + num);   
            }
        }
    }



回答6:


change

for(long i = 2; i <= limit; i++)

to

// add the one for rounding errors in the sqrt function
new_limit = sqrt(limit) + 1;
// all even numbers are not prime 
for(long i = 3; i <= new_limit; i+=2)
{
...
}

Factoring 1,000,000 for example instead of iterating 1,000,000 times the thing only needs to do around 500 iterations.



来源:https://stackoverflow.com/questions/11152127/largest-prime-factor-program-takes-aaaages-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!