Write a program prime_finder1.py
that asks the user to enter a value n
. The program then checks all the values from 2 through n
inclusive and prints out the numbers in that range that are prime.
Recall that a prime is a positive value (2 or higher) that is only divisible by itself and 1. For this program, the strategy should for checking any given number n
should be assuming that the number is prime, possibly with a boolean flag:
is_prime = True
Check all the values less than that number n
to see if they evenly divide into it. If any of them do, we know that the number is not prime and we can change the value of our flag.
is_prime = False
At the end of checking, if is_prime
is still set to True, we’ll know that the number was never divisible and we can identify it as prime. If is_prime
got set to False, however, we’ll know that it wasn’t prime and we can move on to checking the next value.
There are a number of optimizations that you can build in to make the program a bit more efficient.
Sample Interactions:
$ python prime_finder1.py
Enter highest prime value to find: 20
2 is prime!
3 is prime!
5 is prime!
7 is prime!
11 is prime!
13 is prime!
17 is prime!
19 is prime!