Check if Number is Prime
Determine whether one integer is prime with Python. Students reject numbers below two and trace trial division, a flag, and the square-root stopping bound.
1# Take number2num = int(input("Enter a number: "))34# Check prime5if num < 2:6 print("Not prime")7else:8 is_prime = True9 for i in range(2, int(num ** 0.5) + 1):10 if num % i == 0:11 is_prime = False12 break1314 if is_prime:15 print("Prime")16 else:17 print("Not prime")
Output
Enter a number: 17 Prime Enter a number: 15 Not prime
In this one
- Reject values below two
- Stop on a found factor
- Interpret an empty factor range
How it works
- 1
Reject num below two.
- 2
Test factors through the integer square-root bound.
- 3
Print Prime only if no factor cleared the flag.
Edge cases
Is one prime?
Is one prime?
No. The initial num < 2 check rejects it.
Why not test every divisor up to num?
Why not test every divisor up to num?
Any composite has a factor no greater than its square root.
What's going on
A prime is an integer greater than one with exactly two positive divisors. The first branch rejects zero, one, and negative values before any divisor search.
For remaining inputs, a divisor proves the number composite and ends the search. If none is found up to the square root, the number is prime. For two, the divisor range is empty, which correctly leaves the flag true.
Is one prime? No. The initial num < 2 check rejects it.
Why not test every divisor up to num? Any composite has a factor no greater than its square root.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What makes is_prime false?
Pick an answer to check it.
Question 2
Is one prime?
Pick an answer to check it.
Questions people ask
Is one prime?
No. The initial num < 2 check rejects it.
Why not test every divisor up to num?
Any composite has a factor no greater than its square root.
What makes is_prime false?
Finding a divisor.
๐Related Content
- ๐
Phase 2 - Learn Concepts
Review Phase 2 concepts and explanations
- ๐
Phase 2 - Quiz
Test your Phase 2 understanding with quiz questions
- ๐ป
Phase 2 - All Practice Problems
Explore all practice problems for Phase 2
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum