Click here to Skip to main content
15,899,475 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My code successfully counts the number of primes before a given number, n. However, I need a way to improve the speed of it as it isn't efficient for extremely large numbers.

What I have tried:

public class Solution {
    public static int countPrimes(int n) {
        int count = 0;
        for(int i = 2; i < n; i++){
            if(IsPrime( i )){
                count++;
            }
        }
        return count;
    }
    public static boolean IsPrime(int num) {
        for(int i=2;i<=num/2;i++){
            if(num % i == 0){
                return false;
            }
        }
        return true
}
Posted
Updated 8-Aug-16 17:20pm
Comments
CPallini 9-Aug-16 2:26am    
There's no way to improve Java speed. Try using an actual programming language...
(just kidding)

Take advantage of common knowledge about prime numbers.
- After 2, all primes are odd, so no need to test even numbers.
- All compound numbers have a divisor below its square root.
 
Share this answer
 
Comments
CPallini 9-Aug-16 2:25am    
5.
Patrice T 9-Aug-16 2:34am    
Thank you
If you can be satisfied with an approximate number of primes, look into some math theory, going back to Euler, who gave a function for the approximate number of primes less than a given number.

If you really need the exact count, there are better ways to find prime numbers. Look into the sieve methods and others, some of which are discussed here on code project.

Trivially, to improve the IsPrime function you have given here, the upper bound of the for loop should be i <= ceiling(sqrt(num)), because a non-prime number must have two factors, and one of them must be less than or equal to its square root. Also, the division by two should come before the loop, so then the loop may run:
for (i=3; i<=ceiling(sqrt(num)); i=i+2) { ...}
So then you only have to test odd divisors. Twice as fast.
 
Share this answer
 
Comments
CPallini 9-Aug-16 2:25am    
5.
There's more than one way to generate a list of primes. Methods that are FAR faster than the naive method you're using now. I encourage you to Google for prime number generators, like the Sieve of Eratosthenes. You don't have to generate a list of primes that stops exactly at the limit you want. You can generate a list larger than that and then only count up to the number you need.
 
Share this answer
 
Comments
CPallini 9-Aug-16 2:25am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900