Archive

Posts Tagged ‘goldbach conjecture’

Goldbach Conjecture #Java

July 27, 2017 Leave a comment

Return the number of ways to write the given n as the sum of two prime numbers.

Example
For n = 20, the output should be
gold(n) = 2.
There are two ways to represent 20 as the sum of two prime numbers:

3 + 17 = 20,
7 + 13 = 20.


int gold(int n) {
    if ( n <= 2) return 0;
    int res = 0;
    for(int i = 2; i <= n / 2; i++ ){
        if( isPrime(i) && isPrime(n - i) ){
            res++;
        }
    }
    return res;
}
boolean isPrime(int x){
    for (int i = 2; i * i <= x; i++)
        if ( x % i == 0)
            return false;
    return true;
}
Advertisements

Goldbach Conjecture #Ruby

July 27, 2017 Leave a comment

Return the number of ways to write the given n as the sum of two prime numbers.

Example
For n = 20, the output should be
gold(n) = 2.
There are two ways to represent 20 as the sum of two prime numbers:

3 + 17 = 20,
7 + 13 = 20.


require 'prime'
def gold e
    r = 0
    for i in 2..(e/2)
        r += 1 if Prime.prime?(i) && Prime.prime?(e-i)
    end
    r
end