Balanced Prime | Java 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
import java . util . * ; public class GFG { static int MAX = 501 ; public static int balancedprime ( int n ) { boolean [ ] prime = new boolean [ MAX + 1 ] ; for ( int k = 0 ; k < MAX + 1 ; k ++ ) prime [ k ] = true ; 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 < Integer > v = new Vector < Integer > ( ) ; for ( int p = 3 ; p <= MAX ; p += 2 ) if ( prime [ p ] ) v . add ( p ) ; int count = 0 ; for ( int i = 1 ; i < v . size ( ) ; i ++ ) { if ( ( int ) v . get ( i ) == ( ( int ) v . get ( i + 1 ) + ( int ) v . get ( i - 1 ) ) / 2 ) count ++ ; if ( count == n ) return ( int ) v . get ( i ) ; } return 1 ; } public static void main ( String [ ] args ) { int n = 4 ; System . out . print ( balancedprime ( n ) ) ; } }