Prime Numbers between an interval | MATLAB Tutorial
by SAURAB S
Printing all prime numbers between an interval using MATLAB
What is a Prime number?
- A Prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
- It should not be divisible by any other number, else it is composite.
- 1 is neither prime nor composite.
Example:- Prime numbers between
- 1 and 10 are
2, 3, 5, 7
- 10 and 20 are
11, 13, 17, 19
- 30 and 40 are
- 100 and 200 are
101, 103, 107, 109, 113, 127, 131, 137, 139, 149,151, 157, 163, 167, 173, 179, 181, 191, 193, 197,199.
a=input('Enter first no.'); b=input('Enter second no.'); if(a<0||b<0||a>b) error('Error') end for j= 0:b-a flag=0; for i=2:(a+j)/2; if (mod((a+j),i)==0) flag=1; end end if flag==0 fprintf('%d',a+j); fprintf('\n'); end end
- The user should enter two numbers which then becomes the two extreme points of an interval.
- Those two numbers are then stored in two variables.
- The number entered first is divided by every number from 2 to half of the number and then the remainder is taken.
- If the remainder results in 0 then the ‘flag’ is made to be one. This ‘flag’ is used to decide whether a certain number is prime or not.
- If the number makes the flag as one it is a composite number, whereas if it turns out that a number doesn’t turn or change the flag to one then it is not a composite number.
- Above process is repeated for every number between the interval entered by the user and the desired number is printed on the screen.
1. Numbers between 10-100
2.Numbers Between 200-300
3. Error when a greater number is added first and a smaller number later