## Algorithm flowcharted: Prime numbersThis article explains with flow charts the algorithm to create a list of prime numbers. The algorithm lists all prime numbers in a given range. Our algorithm is in Perl, but the principle is not language dependent. ## TheoryA prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. The first few prime numbers are 2, 3, 5, 7, 11, 13 and 17. As it happens, there is no upper limit. ## AlgorithmIt's easy to print a list of prime numbers. Simply go through all the numbers, check if they any of them is prime, and print it. We use a brute-force approach to determine if a number is prime. Below is our prime script in Perl. As you run the script, it prints out all the prime numbers it finds. The printing usually happens on screen rather than on paper.
## Flow chartIn flow chart form, the algorithm looks like this: The flow charts on this page were created by Visustin, a flow chart tool that converts source code to flow charts. ## Flow chart step by stepIn this script, we look for prime numbers in the range 2..1000. For this reason, we set $max = 1000. Then we start looping through the numbers. We start from $n=2 and move towards 1000 one by one. On each round, we increment $n++ until we have reached $max. When that happens, we will have printed our list and the script ends. Inside the loop, for each number $n, we determine if it's prime or not. Here is how we do it. Initially, we assume $n is prime, and therefore let $isprime=1. Then we attempt to prove $n is The chart below is an expanded version of the one above. Inside the loop, you can see how we determine if $n is divisible. The test On the other hand, if the test yields false, we execute the No branch, meaning we increment $i++ and move on to the next integer. We repeat this until the test yields true or no more integers are left. In the latter case, $isprime will have remained 1, and we have found a prime number. Last but not least, if we found a prime number, we print it out. ## Output
The flow charts on this page were created by Visustin, a flow chart tool that converts source code to flow charts. |