Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

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.

IntermediatePhase 2 - Level 2: Number-based Looping LogicExample 8 of 14
check-if-number-is-prime.py
1# Take number
2num = int(input("Enter a number: "))
3
4# Check prime
5if num < 2:
6 print("Not prime")
7else:
8 is_prime = True
9 for i in range(2, int(num ** 0.5) + 1):
10 if num % i == 0:
11 is_prime = False
12 break
13
14 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. 1

    Reject num below two.

  2. 2

    Test factors through the integer square-root bound.

  3. 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.