45.4k views
2 votes
A twin primes is a pair of prime numbers such that the difference between them is 2. For example, 5 and 7 are twin primes, and 17 and 19 is another pair of twin primes. Write a program that finds all the twin primes between 10 and 500, save the results in a two-column matrix, and output result nicely formatted. You can use the built-in function, isprime().

User Finest
by
5.2k points

1 Answer

5 votes

Answer: There is 22 possible combinations.

Explanation:

%a is equal or greater then 11 and it is odd

count=0;

P=[];

for a=11:2:499

b=a+2;

%assume a and b are prime;

prime=1;

%check if a and b are prime

for k=2:ceil(sqrt(b))

%if a OR b is divisible by k, break

%it is not prime

if mod(a, k)==0 | mod(b, k)==0

prime=0;

break;

end

end

if prime

count=count+1;

P(count, :)=[a b];

end

end

fprintf('There is %d possible combinations.\\', count)

display(P)

There is 22 possible combinations.

P =

11 13

17 19

29 31

41 43

59 61

71 73

101 103

107 109

137 139

149 151

179 181

191 193

197 199

227 229

239 241

269 271

281 283

311 313

347 349

419 421

431 433

461 463

User Mehmet Sahin
by
4.2k points