Balanced Prime | Javascript 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
var MAX = 501 ; function balancedprime ( n ) { var prime = Array ( MAX + 1 ) . fill ( true ) ; for ( var p = 2 ; p * p <= MAX ; p ++ ) { if ( prime [ p ] == true ) { for ( var i = p * 2 ; i <= MAX ; i += p ) prime [ i ] = false ; } } var v = [ ] ; for ( var p = 3 ; p <= MAX ; p += 2 ) if ( prime [ p ] ) v . push ( p ) ; var count = 0 ; for ( var i = 1 ; i < v . length ; i ++ ) { if ( v [ i ] == ( v [ i + 1 ] + v [ i - 1 ] ) / 2 ) count ++ ; if ( count == n ) return v [ i ] ; } } var n = 4 ; document . write ( balancedprime ( n ) ) ;