Flowchart for a prime number check
This flowchart checks whether a number n is prime. It tries divisors starting at 2 and stops once i × i is greater than n. It is aimed at students learning loops and conditions, and at developers who want a quick visual before writing code.
Example: Flowchart for checking whether a number is prime: click to open it in the editor and change it.
Steps and decisions in order
- Start: the algorithm begins.
- Read n: input the number to test.
- i = 2: set the first candidate divisor.
- i × i ≤ n?: if No, no divisor was found up to √n, so go to Print "Prime". If Yes, keep testing.
- n mod i = 0?: if Yes, i divides n evenly, so go to Print "Not prime". If No, try the next divisor.
- i = i + 1: increase the divisor and loop back to i × i ≤ n?.
- Stop: both print steps lead here.
Why it only checks up to i × i ≤ n
If n has a factor larger than √n, it must also have a matching factor smaller than √n. So testing divisors from 2 up to √n is enough. Comparing i × i ≤ n avoids a square-root calculation and keeps the loop short. For n = 97, the loop only tries i = 2 to 9.
| n | Path taken | Output |
|---|---|---|
| 9 | i = 2: 9 mod 2 ≠ 0; i = 3: 9 mod 3 = 0 | Not prime |
| 13 | i = 2, 3 fail; i = 4 gives 16 > 13 | Prime |
| 2 | i = 2 gives 4 > 2 right away | Prime |
How to adapt it for your project
- Handle small inputs: as drawn, n = 0 or 1 skips the loop and prints "Prime". Add a decision n < 2? after Read n that leads to Print "Not prime".
- Speed it up: test 2 separately, then start at i = 3 and change i = i + 1 to i = i + 2 so only odd divisors are checked.
- Return a value: replace the two print steps with "return true / false" if you use it as a function.
- Check a range: wrap the whole chart in an outer loop to list all primes up to a limit.
Tip: Trace the chart by hand with n = 1, 2, 4 and a larger prime such as 29 before coding. Edge cases are where most prime-check bugs hide. Open and edit the diagram to add the n < 2 check.
Frequently asked questions
How does a flowchart check if a number is prime?
It reads n, sets i = 2, and repeatedly checks whether n mod i = 0 while i × i ≤ n. If a divisor is found it prints "Not prime". Otherwise it prints "Prime" when the loop ends.
Why does the prime flowchart loop only until i × i ≤ n?
Any factor above √n pairs with one below √n, so checking up to √n finds every possible divisor. Using i × i ≤ n avoids computing a square root.
Does this flowchart work for 0 and 1?
Not as drawn. For n = 0 or 1 the condition i × i ≤ n is false immediately, so it prints "Prime". Add an n < 2 decision after Read n to fix this.
Make your own flowchart with AI →