Search Program on this blog

Thursday 27 August 2015

Write a function called prime_pairs that returns the smallest prime number p smaller than 100,000 such that (p + n) is also prime, where n is a scalar integer and is the sole input argument to the function. If no such number exists, then the function returns -1. You may use the built-in functions, primes and isprime. Note that an efficient solution to this problem, such as the one the grader uses, takes a fraction of a second, but depending on how you do it, yours may be significantly slower.

function p= prime_pairs(n)
%Input n is a scalar integer
%Output p is prime number
%Example p=prime_pairs(22)
flag=0;
A=primes(100000);
l=length(A);
for i=1:l
    if isprime(A(i)+n)==1  %check if p+n is also prime
        p=A(i);
        flag=1;
        return;
    end
end
if flag~=1
    p=-1;
    return;
end

No comments:

Post a Comment