Table of contents
In this post, I will give you some ways to count how many primes number from 1 to R.
A prime number is a number larger than 1 and has exactly two distinct natural number divisors: the number 1 and itself.
Note: I will be using C++ throughout this algorithm.
Brute force
#include <bits/stdc++.h>
using namespace std;
// Algorithm:
// Check every possible from 1 to r
// If it is a prime number then increase variable count by 1
bool isPrime(long long nums) {
// Base case
if(nums < 2) return false;
if(nums <= 3) return true;
// check from 2 to sqrt(nums)
// if nums cannot divide for numbers
// then it is in fact a prime number
for(long long i = 2; i * i <= nums; i++)
if(nums % i == 0)
return false;
return true;
}
int main() {
long long r; // using long long in case if number up to 1e18
cin >> r;
long long counts = 0; // counts prime numbers
// Increment counts if current is a prime number
// every number less than r
for(long long i = 2; i <= r; i++)
if(isPrime(i))
counts++;
// Print the result out
cout << counts;
return 0;
}
Sieve of Eratosthenes
Sieve of Eratosthenes is an ancient algorithm that can find prime numbers with a limit of up to 1e7 numbers in 1 second.
We mark every composite number that is a multiply of a prime number. If there are no numbers left that we can start marking with, we exit the algorithm.
E.g: for prime number 2, we will mark every even number, starting from 4 to any limit.
#include <bits/stdc++.h>
using namespace std;
int main() {
int r;
cin >> r;
int counts = 0;
// Create a variable from to mark numbers
vector<bool> isPrime(r + 1, true);
isPrime[0] = isPrime[1] = false;
// Start with numbers 2 to sqrt(n)
// If current number doesn't mark then
// mark all the numbers which are divisible by it.
for(int i = 2; i * i <= r; i++)
if(isPrime[i])
for(int j = i * i; j <= r; j += i)
isPrime[j] = false;
// Increment counts if current is a prime number
// every number less than r
for(int i = 2; i <= r; i++)
if(isPrime[i])
counts++;
// Print the result out
cout << counts;
return 0;
}
Conclusion
These are some common ways to count prime numbers that I use.
For more information about the sieve of Eratosthenes, you can check its wiki here