Python Is Prime
def / loopPractice

Define is_prime(n) — trial division

A prime is divisible only by 1 and itself. Test by dividing up to √n — no need to check further.

Picture this: test divisors

Try dividing by 2, 3, … If nothing divides evenly, it is prime.

ncandidate
→
try d2 … sqrt(n)
→
n % d == 0?not prime
→
none divideprime

In easy words: What is this task?

You check whether a number has only two factors: 1 and itself. If yes, it is prime.

Where this is used

Used in cryptography, number theory tools, puzzle generators, and algorithm interview problems.

Theory: trial division

  • Any composite number n has a factor ≤ √n, so only check divisors up to int(n**0.5)+1.
  • If any i divides n evenly (n % i == 0), return False.
  • Numbers less than 2 are not prime by definition.

Real world: cryptography

RSA encryption relies on very large prime numbers. Key generation calls a primality test millions of times — the exact function logic you're writing here, just on 512-bit numbers.

Primes 1–50 — green = prime, faded = composite, yellow = your input

is_prime(?) = ?
1def is_prime(n):
2if n < 2: return False
3for i in range(2, int(n**0.5)+1):
4if n % i == 0: return False
5return True

Example Program

1def is_prime(n):
2return n > 1 and all(n%i!=0 for i in range(2, int(n**0.5)+1))
3print(is_prime(17))