Count prime number till N

how to count prime numbers
number of prime numbers less than n
sieve of eratosthenes
count primes python
count prime numbers in python
generate prime numbers
number of primes less than n calculator
prime number theorem

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 in checkprime after i has reached the square root of n. The reason is that if you have found a factor greater than the square root of n, that implies that there was a factor less than the square root of n that should have been found already.

for (int i = 2; i <= Math.sqrt(n); i++) {

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.

Print all prime numbers less than or equal to N, So we check for divisibility only till √n. C++; Java; C#; Python3; PHP. C++. Given a number N. Find number of almost primes from 1 to . A number is called almost if it has exactly two distinct prime factors. Note: The numbers can have any number of non-prime factors but should have exactly two prime factors. Examples: Input: N = 10 Output: 2 Explanation: 6, 10 are such numbers. Input: N = 21 Output: 8

Primes, other than 2, are never even. Primes are only divisible by 1 and iteslef.

Also you can check up to it's sqrt. If you find nothing by then then it's a prime.

        public bool IsPrime(double num)
    {
        bool isprime = true;
        double limit = Math.Sqrt(num);

        if (num % 2 == 0)
            return num == 2;

        if (num == 3 || num == 5 || num == 7)
            return true;

        for (int i = 3; i < limit; i++)
            if (num % 1 == 0)
                return false;

        return isprime;
    }

Count Primes in Ranges, Given a range [L, R], we need to find the count of total numbers of prime numbers in the range [L, R] where 0 <= L <= R Then we compute a prefix array to store counts till every value before limit. Create a boolean array "prime[0..n]". A. 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.).

Sieve of Eratosthenes is a very famous and efficient algorithm to generate all small prime numbers up to around 1-10 million. This is an ancient algorithm given by a Greek mathematician named Eratosthenes.

 public class CountPrimes {

  public static void main(String[] args) {
    System.out.println(countPrimes(1000000));
  }

  public static int countPrimes(int n) {
    boolean[] primes = new boolean[n +1];

    for(int i = 0 ; i <= n ; i++) {
        primes[i] = true;
    }

    primes[0] = false;
    primes[1] = false;

    for(int i = 2 ; i * i <= n ; i++) {
        if(primes[i]) {
            for(int j = i ; i * j <= n ; j++) {
                primes[j * i ] = false;
            }
        }   
    }

    int primeCounts = 0;
    for(int i = 2 ; i <= n ; i++) {
        if(primes[i]) {
            primeCounts++;
        }
    }

    return primeCounts;
  }

}

How to find number of prime numbers up to to N?, π(n)≈nln(n). where π(n) is the number of primes less than n and ln(n) is the natural logarithm of n. (Googling 'Prime Number Theorem' will tell you more! But this  that means if x is of form 2mn+m+n then f(x) will give composite numbers otherwise prime no. so reduce the domain of f(x) from N to N-A where A is set of all no. that can be represented as 2mn+m+n then we will get prime here A can be calculated easily. For example if m=1 n=1. Then 2mn+m+n that is 2(1)(1)+1+1=4. So for f(4)=9 which is composite. But f(1)=3

You can store found primes into list and make further checks only against them (Sieve of Eratosphenes):

import java.util.ArrayList;
import java.util.List;

public class PrimeNotillN {
    public static void main(String[] args) {
        int n = 1000000;
        int count = 0;
        List<Integer> primes = new ArrayList<>();

        for (int i = 2; i < n; i++) {
            boolean res = checkprime(primes, i);
            if (res) {
                count++;
                primes.add(i);
            }
        }
        System.out.println("total prime number till " + n + " is " + count);
    }

    private static boolean checkprime(List<Integer> primes, int n) {
        int fence = (int) Math.sqrt(n);
        for (int prime : primes) {
            if (n % prime == 0) {
                return false;
            }
            if (prime >= fence)
                break;
        }

        return true;
    }
}

Calculate the number of primes up to n, &now); printf("pi(x) = %9d real time:%9ld ns\n", result , ns(now) Then, we compute xpk for all k in (π(3√x),π(√x)], and count the primes up  A simple solution is to traverse all numbers from 1 to n. For every number, check if it is a prime. If yes, add it to result. An efficient solution is to use Sieve of Eratosthenes to find all prime numbers from till n and then do their sum.

Using the sieve of eratoshtenes approach and maintaining the cache of all prime numbers found

    public int countPrimes(int n) {
    if(n==0){
        return 0;
    }else{
        boolean[] isPrime=new boolean[n];
        for(int i=2;i<n;i++){
            isPrime[i]=true;
        }

        for(int i=2;i*i<n;i++){
           if(!isPrime[i]){
               continue;
           }
            for(int j=i*i;j<n;j+=i){
                isPrime[j]=false;
            }
        }

        int counter=0;
        for(int i=2;i<n;i++){
            if(isPrime[i]){
                counter++;
            }
        }

        return counter;

    }
}

How many primes are there? - The Prime Pages, The prime number theorem tells us the number of primes less than n is about 1/ln​(n). the value of π(x) can be found by finding and counting all of the primes. Step by step descriptive logic to print all prime numbers between 1 to n. Input upper limit to print prime numbers from user. Store it in some variable say end. Run a loop from 2 to end, increment 1 in each iteration. The loop structure should be like for(i=2; i<=end; i++). Inside the loop for each iteration print value of i if it is prime number. Program to print prime numbers between 1 to n

Count Primes, The runtime complexity of isPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better? Show Hint 2. TIP: Please refer Java Program to Check Prime Number article to understand the steps involved in checking Prime Number. Java Program to Print Prime Numbers from 1 to N using For Loop. This Java program allows the user to enter any integer value. Next, this Java program displays all the Prime numbers from 1 to 100 using For Loop.

C program to generate prime numbers upto n, We use two for loops one for counting the numbers upto n and second nested for loop for validating if the number is prime or not.Then the procedure is same as  In mathematics, the prime-counting function is the function counting the number of prime numbers less than or equal to some real number x. It is denoted by π (x) (unrelated to the number π). The values of π (n) for the first 60 positive integers

LeetCode – Count Primes (Java), Count the number of prime numbers less than a non-negative number, n Java Solution 1 This solution exceeds time limit. public int countPrimes(int n) The prime number theorem tells us the number of primes less than n is about 1/ln(n). This pages includes history, theorems, related results and open questions. PrimePages. 5000 Largest. 5000 LargestTop 20 PrimesProver BiosSearch Primes.

Comments
  • This is not fixable without fundamentally rewriting. e.g. changing algorithms. you're using one of the slowest possible methods...
  • You might want to research the Sieve of Eratosthenes.
  • One quick and easy way to reduce your execution time would be to change your for loop to increment i by 2 each time (to skip checking even numbers). Note that this would require starting at 3 instead of 2, with count = 1; initially.
  • Not related to your question since it has already been correctly addressed, but inside your for loop you could just use if(checkprime(i)) count++; saves some space, gets rid of unnecessary variables, looks nice
  • Nope Nope Nope! this takes alotttttttttttt of time. Sieve is the key to do this.
  • I*d use i*i <= n instead of i <=Math.sqrt(n) just from an intuition that squaring is faster than taking the square root (probably does not matter much on today's CPUs, though). Also keep in mind that with the Sieve of Eratosthenes, you will trade speed for memory usage (especially if the number is large).
  • This optimization combined with skipping even numbers will result in an algorithm with acceptable performance in my opinion. No it's not terribly fast, but it will be better the twice as fast as it would be without the optimizations as you are removing more than half of the numbers you check that will fail.
  • i < limit is wrong. num % 1 == 0 is always true. using doubles to represent primes is not good.
  • no algorithm which makes checks (i.e. tries to divide) by whatever numbers is Sieve of Eratosthenes. the whole point to it is that no checks need be made. composites are generated by repeated addition, and what's left are automatically primes. if you test divide, complexity significantly worsens.