Home > Mobile >  Display all prime number pairs whose sum is N
Display all prime number pairs whose sum is N

Time:04-28

I am working on a code for Goldbach Conjecture to display the prime number pairs whose sum is equal to a positive even number N. I was able to find these prime number pairs but I want to print all these prime number pairs equal to N in one single line.

Any clue on how I would be able to work it out to achieve the desired result? This is the code I have worked out:

function goldB(N)
    for x = 6:2:N
        P = primes(x);
        for y = 1:length(primes(x))
            for z = 0:(length(P)-y)
                if P(y)   P(y z) == x
                    fprintf('\n%d = %d   %d',x,P(y),P(y z));
                end
            end
        end
    end
end

CodePudding user response:

I think the easiest way is to change the function call so that it prints the target number separately (along with a newline), and then also prints all the pairs associated with it (as they are found):

function goldB(N)
    for x = 6:2:N
        fprintf('\n%d', x);
        P = primes(x);
        for y = 1:length(primes(x))
            for z = 0:(length(P)-y)               
                if P(y)   P(y z) == x
                    fprintf('= %d   %d', P(y), P(y z));
                end
            end
        end
    end
end
  • Related