
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Alternate Primes till N in C++?
Here we will see how to print all alternate prime numbers till N. The alternate prime numbers are like below. Suppose N = 15. So the prime numbers till N are {2, 3, 5, 7, 11, 13}. The alternate prime numbers are {2, 5, 11}. Let us see how we can solve this problem.
Algorithm
printAlternatePrime(N)
Begin define one Boolean array prime of size N + 1, and fill with 1. for p := 2, p^2 is less than N, increase p by 1, do if prime[p] is true, then for all multiples of p, make the position 0 in prime array end if done set the flag for p := 2 to n, do if prime[p] is true, then if flag is set, then print p, and reset the flag else set the flag end if end if done End
Example
#include<iostream> using namespace std; void printAlternatePrime(int n) { bool prime[n + 1]; for(int i = 0; i<=n; i++) { prime[i] = true; } for (int p = 2; p * p <= n; p++) { if (prime[p]) { for (int i = p * 2; i <= n; i += p) //all multiples will be false prime[i] = false; } } bool prime_flag = true; for (int p = 2; p <= n; p++) { if (prime[p]) { if (prime_flag) { cout << p << " "; prime_flag = false; } else { prime_flag = true; //set to print next prime } } } } main() { int n; cout << "Enter upper limit: "; cin >> n; cout << "Alternate prime numbers are: "; printAlternatePrime(n); }
Output
Enter upper limit: 20 Alternate prime numbers are: 2 5 11 17
- Related Articles
- Python Getting sublist element till N
- Print all safe primes below N in C++
- Print all Proth primes up to N in C++
- Generate a list of Primes less than n in Python
- Maximum Primes whose sum is equal to given N in C++
- Find the sum of all Truncatable primes below N in Python
- How to Alternate Row Colour Based on Group in Excel?\n
- Java Program to Find Even Sum of Fibonacci Series till number N
- Swift Program to Find Sum of Even Fibonacci Terms Till number N
- Count Primes in Python
- Minimum number of single digit primes required whose sum is equal to N in C++
- Program for converting Alternate characters of a string to Upper Case.\n
- Alternate Key in RDBMS
- Count Primes in Ranges in C++
- Count numbers < = N whose difference with the count of primes upto them is > = K in C++

Advertisements