This code works fine to count prime number till n. The problem is when n value is large like 1000000 or more, then it takes long time to execute and print the output (more than 30 secs.). I want to fix this issue. Any help would be great. Below is the code:
public class PrimeNotillN {
public static void main(String[] args) {
int n = 1000;
int count = 0;
for (int i = 2; i < n; i++) {
boolean res = checkprime(i);
if (res == true)
count++;
}
System.out.println("total prime number till " + n + " is " + count);
}
private static boolean checkprime(int n) {
if (n == 1)
return false;
else {
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
}
The easiest change to make is to end the
for
loop incheckprime
afteri
has reached the square root ofn
. The reason is that if you have found a factor greater than the square root ofn
, that implies that there was a factor less than the square root ofn
that should have been found already.Additionally, if you need more speed, the best algorithm for printing all prime numbers up to a limit is the Sieve of Eratosthenes. That involves replacing what you have. You'll need an array in which you'll mark which numbers are composite. Starting with 2, you will mark all multiples of 2 as composite. Moving through the array, if you find a number that isn't marked composite, it's prime and you can print it. With each prime you encounter, you will mark all of that prime's multiples as composite as well.