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;
}
}
}