Matlab Tutorials | Examples
Practice 5:
Prime pairs that yield primes
A prime number is a number that can be divided without remainder only to 1 and itself. You can find out that a number p is prime by dividing it by all numbers between
2 and p, and verifying that the remainders in all such divisions are non-zero.
Consider the pairs of successive prime numbers, such as (2, 3), (3, 5), (5, 7), (7, 11), (11, 13), (13, 17), etc. Write a program that finds the first ten successive prime pairs (p, q), such that pq+p+q is also a prime number.
While writing this program, you are expected NOT to use vectors (arrays) or any MATLAB functions that automatically give you prime numbers, such as primes(), isprime(), etc.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
%Prime pairs that yield primes clc; clear; n=2; b = 0; j=0; while(j < 10) result = true; %Reset boll variable for each iteration result2 = true; for i=2:n-1%Finding first prime numbers if (mod(n,i)==0) %Looking the divideablity result = false; %If it is divide mak result the false end end if result % if result is true in this iteration n is a prime number if(b>0) %Eliminition first variable new = (b*n)+b+n; % pq+p+q find this value for i2 = 2:sqrt(new) % loking the dividablity between 2 to sqrt(new) if (mod(new,i2)==0)%Looking the divideablity result2 = false;%If it is divide mak result2 the false end end if (result2)%if result2 is true in this iteration new number is a prime number j = j+1;%finding one of them therefore increase j fprintf('For (%g,%g), %gx%g+%g+%g= %g is a prime.\n',b,n,b,n,b,n,new); else%if result2 is false in this iteration new number is a NOT prime number fprintf('For (%g,%g), %gx%g+%g+%g= %g is NOT a prime.\n',b,n,b,n,b,n,new); end end b = n;%Storage the prime number in b for using after end n = n+1; %increase n for loop end |