Ramanujan Prime | Javascript program to find Ramanujan numbers ; FUnction to return a vector of primes ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already been marked . ; Print all prime numbers ; Function to find number of primes less than or equal to x ; Binary search to find out number of primes less than or equal to x ; Function to find the nth ramanujan prime ; For n >= 1 , a ( n ) < 4 * n * log ( 4 n ) ; We start from upperbound and find where pi ( i ) - pi ( i / 2 ) < n the previous number being the nth ramanujan prime ; Function to find first n Ramanujan numbers ; Get the prime numbers ; Driver code
const MAX = 1000000 ; function addPrimes ( ) { let n = MAX ; let prime = new Array ( n + 1 ) . fill ( true ) ; for ( let p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( let i = p * p ; i <= n ; i += p ) prime [ i ] = false ; } } let ans = [ ] ; for ( let p = 2 ; p <= n ; p ++ ) if ( prime [ p ] ) ans . push ( p ) ; return ans ; } function pi ( x , v ) { let l = 0 , r = v . length - 1 , m , inn = - 1 ; while ( l <= r ) { m = parseInt ( ( l + r ) / 2 ) ; if ( v [ m ] <= x ) { inn = m ; l = m + 1 ; } else { r = m - 1 ; } } return inn + 1 ; } function Ramanujan ( n , v ) { let upperbound = 4 * n * parseInt ( ( Math . log ( 4 * n ) / Math . log ( 2 ) ) ) ; for ( let i = upperbound ; ; i -- ) { if ( pi ( i , v ) - pi ( parseInt ( i / 2 ) , v ) < n ) return 1 + i ; } } function Ramanujan_Numbers ( n ) { let c = 1 ; let v = addPrimes ( ) ; for ( let i = 1 ; i <= n ; i ++ ) { document . write ( Ramanujan ( i , v ) ) ; if ( i != n ) document . write ( " " ) ; } } let n = 10 ; Ramanujan_Numbers ( n ) ;