Balanced Prime | CPP Program to find Nth Balanced Prime ; Return the Nth balanced prime . ; Sieve of Eratosthenes ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; storing all primes ; Finding the Nth balanced Prime ; Driven Program
#include <bits/stdc++.h> NEW_LINE #define MAX  501 NEW_LINE using namespace std ; int balancedprime ( 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 = 4 ; cout << balancedprime ( n ) << endl ; return 0 ; }