
- 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
Print all safe primes below N in C++
In this problem, we are given an integer N and we have to print all safe prime number whose values are less than N.
A safe prime number is a prime number which can be represented as [(2*p)- 1] where p is also a prime number.
Examples − 5[(2*2) +1] , 7[(2*3)+1].
Let’s take a few examples to understand the problem better −
Input: N = 12 Output: 5 7 11.
To solve this problem, we will find all the prime numbers less than N(for this we will use Sieve of Eratosthenes). And check if the prime number is a safe prime number or not and print if it is a safe prime number.
Example
#include <bits/stdc++.h> using namespace std; void printPrime(int n){ cout<<n<<"\t"; } void generateSafePrimes(int n){ int prime[n + 1]; for (int i = 2; i <= n; i++) prime[i] = 1; prime[0] = prime[1] = 0; for (int p = 2; p * p <= n; p++) { if (prime[p] == 1) { for (int i = p * 2; i <= n; i += p) prime[i] = 0; } } for (int i = 2; i <= n; i++) { if (prime[i] != 0) { int temp = (2 * i) + 1; if (temp <= n && prime[temp] != 0) prime[temp] = 2; } } for (int i = 5; i <= n; i++) if (prime[i] == 2) printPrime(i); } // Driver code int main(){ int n = 34; cout<<"safe Prime numbers less than "<<n<<" are :\n"; generateSafePrimes(n); return 0; }
Output
Safe Prime numbers less than 34 are −
5 7 11 23
- Related Articles
- Print all Proth primes up to N in C++
- Print all multiplicative primes
- Find the sum of all Truncatable primes below N in Python
- Alternate Primes till N in C++?
- Find all the angles in the figure given below."\n
- Print all n-digit strictly increasing numbers in C++
- Windows in safe mode troubleshoots all system issues
- Print all n digit patterns formed by mobile Keypad in C++
- Queries to Print All the Divisors of n using C++
- Print all prime numbers less than or equal to N in C++
- Print all possible sums of consecutive numbers with sum N in C++
- Generate a list of Primes less than n in Python
- How to understand StringBuffer is thread-safe and StringBuilder is non-thread-safe in Java?\n
- What is a Type-safe Enum in Java?\n
- In the figure below..."\n

Advertisements