
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
Balanced Prime in C++
Balanced prime number is a prime number that has the same difference for its previous and next prime numbers. i.e. it is the mean of the nearest next prime and previous prime.
For a prime number to be a balanced prime, it should follow the following formula −
Pn = (P(n-1) + P(n+1)) / 2
Where n is the index of the prime number pn in the ordered set of a prime number.
The ordered set of prime numbers: 2, 3, 5, 7, 11, 13,….
First, balanced primes are 5, 53, 157, 173 , …
In this problem, we are given a number n and we have to find an nth balanced prime number.
Let’s take an example,
Input : n = 3 Output : 157
For this will generate prime numbers and store it in an array. We will find whether the prime number is a balanced prime or not. If it increases the count and if the count is equal to n, print it.
Example
#include<bits/stdc++.h> #define MAX 501 using namespace std; int balancedprimenumber(int n){ bool prime[MAX+1]; memset(prime, true, sizeof(prime)); for (int p = 2; p*p <= MAX; p++){ if (prime[p] == true) { for (int i = p*2; i <= MAX; i += p) prime[i] = false; } } vector<int> v; for (int p = 3; p <= MAX; p += 2) if (prime[p]) v.push_back(p); int count = 0; for (int i = 1; i < v.size(); i++){ if (v[i] == (v[i+1] + v[i - 1])/2) count++; if (count == n) return v[i]; } } int main(){ int n = 3; cout<<balancedprimenumber(n)<<endl; return 0; }
Output
157