Check for prime number (1 and n exclusion technique)
Check if a number has only two factors 1 and the number itself. The 1 and n exclusion technique does not test division with these two obvious divisors and does it for all other possible divisors.
Learning Objectives
- Concept of prime number.
- Successive checking with divisors.
- Concept of checking division by other numbers and not by numbers that are pre-known to be the divisors.
Program Approach
- Will check division with numbers other than those which are surely the divisors of any numbers that are 1 and the number itself.
- Manual exclusion of 0, 1 and negative numbers in the if condition.
Source Code
|
|
Run Output
Code Understanding
for(int i=2;i<=n/2;i++)
Since a prime number can begin from 2, the check of successive division by divisors can begin for 2 and go up to the highest possible divisor other than the number itself. The highest possible divisor could be just half the number other than the number so loop till n/2 is sufficient.
if(n%i==0) dc++;
This checking starts from 2 and goes up to half of number so check from division with 1 and number itself is excluded. if other than 1 and the number any other divisor is there, the divisor count will increase, else it will remain 0.
if(dc>0 || n<2) cout<<“Not Prime”; else cout<<“Prime”;
If there is any increase in divisor count then number is certainly not a prime as it has another divisor other than 1 and number. Also numbers below 2, which means 0, 1 and all negative numbers are excluded.
Notes
This program follows a unique approach in prime number testing. A prime number has only two divisors. So this code excludes check for these two divisors. This means that a number is prime if it has any other divisor than the most well known divisor. That means the divisor count more than 0 will prove that number is not prime
Suggested Filename(s): prime.cpp, checkprime.cpp
Created: 2-Dec-2017 22:35 | Updated: 15-Sep-2018 13:56|
