Prime Number Checker Using a Loop

Medium ⏱ 12 min 55% acceptance ★★★★☆ 4.4
Write a function is_prime(n) that returns True if n is a prime number and False otherwise, using a for loop that checks divisibility up to the square root of n for efficiency.

Examples

Example 1
Input
is_prime(17)
Output
True
Explanation

17 has no divisors other than 1 and itself.

Example 2
Input
is_prime(15)
Output
False
Explanation

15 = 3 * 5.

Example 3
Input
is_prime(1)
Output
False
Explanation

By definition 1 is not prime.

Constraints

  • n is a positive integer.

Topics

Loopsfor looploop-else

Companies

GoogleAmazon

Hints

Hint 1

Numbers less than 2 are never prime.

Hint 2

You only need to test divisors up to int(n ** 0.5) + 1 for efficiency, though testing all up to n-1 is also acceptable.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.