
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count Almost Prime Numbers from 1 to n in C++
Suppose we have a number N. We have to find almost prime numbers in range 1 to N. A number is called almost prime when it has exactly two distinct factors. The numbers can have any number of non-prime factors, but should be two prime factors. So if N is 2, then output will be 2. There are two numbers 6 and 10.
Here we will use the Sieve of Eratosthenes approach. Please check the following implementation to get better idea.
Example
#include<iostream> #define N 100005 using namespace std; bool prime[N]; void SieveOfEratosthenes() { for(int i = 0; i<N; i++) prime[i] = true; prime[1] = false; for (int i = 2; i * i < N; i++) { if (prime[i] == true) { for (int j = i * 2; j < N; j += i) prime[j] = false; } } } int countAlmostPrime(int n) { int result = 0; for (int i = 6; i <= n; i++) { int div_count = 0; for (int j = 2; j * j <= i; j++) { if (i % j == 0) { if (j * j == i) { if (prime[j]) div_count++; }else { if (prime[j]) div_count++; if (prime[i / j]) div_count++; } } } if (div_count == 2) result++; } return result; } int main() { SieveOfEratosthenes(); int n = 21; cout << "Number of almost primes in range 1 to "<<n << " is: " << countAlmostPrime(n); }
Output
Number of almost primes in range 1 to 21 is: 8
Advertisements