# Prime Numbers Generating Formula using Matlab

This is a sample on Prime Numbers Generating Formula in Matlab. Here, the tutor is demonstrating the process of generating prime numbers.  The generation of prime numbers is correlated to a formula that accepts integral values. Prime numbers are generated using the formula meeting certain constraints. The whole process has been automated using Matlab.

SOLUTION : –

clc

clear all

close all

i=1;

while 1     % This loop is for iterating over integers

x = i*i + i + 41;

flag=0;

% For checking whether x is prime or not

for j=2:floor(sqrt(x))   % Because if x is not prime, then it will have divisor between 2 and [sqrt(x)]

if(mod(x,j)==0)

flag=1;

break;

end

end

% If it is prime then stop the loop

if(flag == 1)

disp([‘Smallest value of n for which equation fails to produce prime number is ‘,num2str(i),’. For this equation generates ‘,num2str(x),’, which is not prime.’]);

break;

end

i=i+1;  % Checking for next integer

end

% Checking whether next 100 numbers are prime or not

for k=i+1:i+100

x = k*k + k + 41;

flag=0;

% For checking whether x is prime or not

for j=2:floor(sqrt(x))   % Because if x is not prime, then it will have divisor between 2 and [sqrt(x)]

if(mod(x,j)==0)

flag=1;

break;

end

end

% If it is not prime then stop the loop

if(flag==1)

disp([‘No it does not generate prime for n=’,num2str(k),’. For this equation generates ‘,num2str(x),’, which is not prime.’]);

break;

end

end

% If all of next 100 numbers are prime

if(flag==0)

disp([‘It generates prime numbers for next 100 values of n.’]);

end