Program for Goldbachâ €™ s Conjecture ( Two Primes with given Sum ) | Javascript program to implement Goldbach 's conjecture ; Array to store all prime less than and equal to 10 ^ 6 ; Utility function for Sieve of Sundaram ; In general Sieve of Sundaram , produces primes smaller than ( 2 * x + 2 ) for a number given number x . Since we want primes smaller than MAX , we reduce MAX to half . This array is used to separate numbers of the form i + j + 2 * i * j from others where 1 <= i <= j ; Main logic of Sundaram . Mark all numbers which do not generate prime number by doing 2 * i + 1 ; Since 2 is a prime number ; Print other primes . Remaining primes are of the form 2 * i + 1 such that marked [ i ] is false . ; Function to perform Goldbach 's conjecture ; Return if number is not even or less than 3 ; Check only upto half of number ; find difference by subtracting current prime from n ; Search if the difference is also a prime number ; Express as a sum of primes ; Finding all prime numbers before limit ; Express number as a sum of two primes
let MAX = 10000 ; let primes = new Array ( ) ; function sieveSundaram ( ) { let marked = new Array ( parseInt ( MAX / 2 ) + 100 ) . fill ( false ) ; for ( let i = 1 ; i <= ( Math . sqrt ( MAX ) - 1 ) / 2 ; i ++ ) for ( let j = ( i * ( i + 1 ) ) << 1 ; j <= MAX / 2 ; j = j + 2 * i + 1 ) marked [ j ] = true ; primes . push ( 2 ) ; for ( let i = 1 ; i <= MAX / 2 ; i ++ ) if ( marked [ i ] == false ) primes . push ( 2 * i + 1 ) ; } function findPrimes ( n ) { if ( n <= 2 n % 2 != 0 ) { document . write ( " " ) ; return ; } for ( let i = 0 ; primes [ i ] <= n / 2 ; i ++ ) { let diff = n - primes [ i ] ; if ( primes . includes ( diff ) ) { document . write ( primes [ i ] + " " + diff + " " + n + " " ) ; return ; } } } sieveSundaram ( ) ; findPrimes ( 4 ) ; findPrimes ( 38 ) ; findPrimes ( 100 ) ;