Optimize calculation of prime numbers [duplicate]

让人想犯罪 __ 提交于 2019-12-10 19:33:58

问题


I am trying Problem 3 from Project Euler and my algorithm is far too slow. Does anyone know how to optimize this? The number I am trying to calculate up to is 600851475143L. It takes forever to calculate this so I need a way to speed up the calculations.

LOGIC:

  • Go through all the numbers from 3 until that number-1
  • For each of these numbers check if they are prime by dividing them by all the numbers in between and if they dont divide by any of them then they are prime.
  • If prime then add them to an array.

    public static void problem3(long number){
    
    long number2 = number;
    long sqrtNumber = (long)Math.sqrt(number2);
    
    
    int indexNum = 1;
    boolean isPrime = false;
    
    int primeNums[] = new int[2];
    primeNums[0] = 2;
    
    //puts prime numbers into an array
    for(int y = 3; y < sqrtNumber; y++){
       isPrime=true;
       for(int theNum = 2; theNum < y; theNum++){
           //if y divides evenly by any number then it is not prime         
           if(y%theNum==0){
               //dont store in array
               isPrime=false;
               break;
           }
       }
    
       if(isPrime == true){
           //add to array
           System.out.println(y);
           //put y in the array and exapnd the array
           //System.out.println("y: " + y);
           primeNums[indexNum] = y;
    
           int[] newArray = new int[primeNums.length + 1];
           System.arraycopy(primeNums, 0, newArray, 0, primeNums.length);
    
           primeNums = newArray;
    
           indexNum++;
       }
    }
    

********** UPDATE **************

I calculated up to the square root which sped up the calculations a lot but I also done something else which was to add a break statement in the forloop to break once I discovered the number was not prime. I edited the code above to reflect these changes.

My algorithm is still wrong for calculating the prime factors though so I will need to have a look at it and maybe raise a new question.



回答1:


You don't have to divide by every number. You only have to divide by each prime number between 2 and the square root of your number.




回答2:


The first thing you can do is only test possible factors up through the square root of the number that you're testing, because if you find a factor greater than the square root, then you should have found a factor less than the square root.

If you need additional performance, then use the Sieve of Eratosthenes. That allows you to use the results of previous primes to cut down the work on determining if larger numbers are prime.



来源:https://stackoverflow.com/questions/15649854/optimize-calculation-of-prime-numbers

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