Archive

Archive for the ‘Algoritmo’ Category

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

Simple Moore Majority Algorithm

April 13, 2016 Leave a comment

Assuming there is always a majority number and that the array has length > 0


public int mooreMajority(int nums[]){
        int result = 0, count = 0;
        for(int x : nums){
            if(count == 0) result = x;
            if(x == result) count++;
            else count--;
        }
        return result;
}