- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print all Proth primes up to N in C++
In this problem, we are given an integer N and we have to print all proth prime numbers less than or equal to N.
Proth Prime Number
A proth prime number is a positive integer whose value can be represented as n = k* 2n + 1. where k is an odd positive integer and n is a positive integer and both satisfy the 2n > k.
Examples − 3, 5, 13…..
Let’s take an example to understand the topic better −
Input: N = 23 Output: 3, 5, 13, 17.
For this, we will find all the prime numbers less than N(for this we will use sieve of Eratosthenes). And check if each of the prime numbers is proth number or not. And print all the proth numbers.
Example
#include <bits/stdc++.h> using namespace std; int prime[1000]; void SieveOfEratosthenes(int n){ for (int i = 1; i <= n + 1; i++) prime[i] = true; prime[1] = false; for (int p = 2; p * p <= n; p++) { if (prime[p] == true) { for (int i = p * p; i <= n; i += p) prime[i] = false; } } } bool isTwosExponent(int n){ return (n && !(n & (n - 1))); } bool isaProthNumber(int n){ int k = 1; while (k < (n / k)) { if (n % k == 0) { if (isTwosExponent(n / k)) return true; } k = k + 2; } return false; } bool isaProthPrime(int n){ if (isaProthNumber(n - 1)) { if(prime[n]) return true; else return false; } else return false; } int main(){ int n = 23; cout<<"Proth Prime Numbers less than or equal to "<<n<<" are :\n"; SieveOfEratosthenes(n); for (int i = 1; i <= n; i++) if (isaProthPrime(i)) cout<<i<<"\t"; return 0; }
Output
Proth Prime Numbers less than or equal to 23 are −
3 5 13 17
Advertisements