Check whether a positive integer is prime in O(sqrt(n)) time

Quick Overview

Decide whether a positive integer up to one billion is prime while checking candidate divisors only up to its square root. It tests the factor-pair argument behind that bound, correct handling of 1, 2 and perfect squares, and a loop condition free of off-by-one errors.

Check whether a positive integer is prime in O(sqrt(n)) time

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

Given a positive integer `n`, determine whether it is a prime number. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Implement the check in $O(\sqrt{n})$ time, testing candidate divisors only up to the square root of `n`. ### Function Signature ```python def is_prime(n: int) -> bool: ``` ### Rules - Return `True` when `n` is prime and `False` otherwise. - `1` is not prime. ### Constraints - `1 <= n <= 10^9` ### Examples ```text Input: n = 29 Output: True ``` The square root of 29 is a little above 5, so the only candidates are 2 through 5. None of them divides 29, so it is prime. ```text Input: n = 15 Output: False ``` 15 is 3 times 5, so 3 is a divisor other than 1 and 15. ```text Input: n = 25 Output: False ``` 25 is 5 times 5. Its only divisor besides 1 and 25 equals the square root exactly, so the square root itself has to be tested.

Overview: Decide whether a positive integer up to one billion is prime while checking candidate divisors only up to its square root. It tests the factor-pair argument behind that bound, correct handling of 1, 2 and perfect squares, and a loop condition free of off-by-one errors.

Nov 24, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Given a positive integer n, determine whether it is a prime number.

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.

Implement the check in O(n)O(\sqrt{n}) time, testing candidate divisors only up to the square root of n.

Function Signature

def is_prime(n: int) -> bool:

Rules

  • Return True when n is prime and False otherwise.
  • 1 is not prime.

Constraints

  • 1 <= n <= 10^9

Examples

Input: n = 29
Output: True

The square root of 29 is a little above 5, so the only candidates are 2 through 5. None of them divides 29, so it is prime.

Input: n = 15
Output: False

15 is 3 times 5, so 3 is a divisor other than 1 and 15.

Input: n = 25
Output: False

25 is 5 times 5. Its only divisor besides 1 and 25 equals the square root exactly, so the square root itself has to be tested.