Lesson 4
Repeated Practice Makes Perfect
Chapter 6: More applied problems
Checking for prime numbers
Is programming getting more interesting now? I hope so!
Let us try one more mathematical problem.
This time, write a program to check whether an integer entered by a user is a prime number.
I will be more hands off this time! 😄
But here are some tips:
Step 1 - understand the problem. Input? Output? Task/objective?
Step 2 - to be able to solve this problem, you will need to make sure you know the official definition of a prime number (and also, is 0 or 1 a prime number?) I will let you check this yourself. Then try to come up with an algorithm to check whether a number is prime. It can be an exhaustive search for your first attempt - there is no need to be too clever at this stage!
Step 3 - implement the algorithm in Python! Remember - test/debug as you code!
Step 4 - test your program to make sure it works. If not, go back to earlier steps. It could be your implementation that is wrong (Step 3), or it could be your algorithm itself that is flawed (Step 2)!
Have fun with this challenge! And I will continue the lesson with you when you are done! Remember - do not start implementing your algorithm until you truly understand what you are trying to implement!
Sample run #1
Please enter an integer: 5
5 is a prime number
Sample run #2
Please enter an integer: 24
24 is not a prime number