CSE 107 - Introduction to Computer Science
Designing Algorithm, Flow Chart and
Coding for a Problem
Presidency University
Finding out if a number is prime
A number is prime if it has no
other factor except for 1 and
itself.
To find out if a number n is
prime, you have to try out
several numbers and check if
any of those numbers is a factor
of n.
Finding out if a number is prime
But how many numbers should we
try?
Notice that, for any factorization
technique, we stop when the number
on the left is greater than the number
on the right. We can see that as the
number on left gets bigger, the
number on the right becomes smaller.
But when does the number on the left
get bigger than the one on the right?
Finding out if a number is prime
But when does the number
on the left get bigger than
the one on the right?
- When the number on the left
crosses the square root of n
- 25 = 5 X 5 , 36 = 6 X 6.
- 24= 4.89 … X 4.89 …
- After the square root, the
number on the left must
Finding out if a number is prime
So the maximum number to try out
is the floor of the square root of n
- 1 is the factor of all integer numbers.
So we should start from 2.
- Starting from 2, we have to try out
all numbers till the root of n.
- If there is any number in that range
which is a factor of n, then n is
composite.
- If there is no number in the range
which is a factor of n, then n is
Algorithm
Flow
S-1: Start. Chart
S-2: Read n.
S-3: sqrt_n = √n.
S-4: i=2.
S-5: Check if i>sqrt_n.
If so, go to step 9.
Otherwise, go to step 6.
S-6: x = n%i.
S-7: Check if x==0.
If so, go to step 10.
Otherwise, go to step 8.
S-8: i=i+1.
Go to step 5.
S-9: Print “Prime”
Go to step 11
S-10: Print “Composite”
S-11: End
Coding in Python
Try Yourself!
END OF SLIDES