DevPath

← All problems

Prime Number Check

Easy math

Description

Return true if n is a prime number (greater than 1 with no divisors other than 1 and itself).

Constraints

0 <= n <= 10^9

Examples

Input: n = 29

Output: true

Hints (1)
  • Trial divide up to the square root; check 2 separately.

Solutions

Trial division to the square root. · Time O(sqrt n) · Space O(1)

func isPrime(n int) bool {
    if n < 2 {
        return false
    }
    if n%2 == 0 {
        return n == 2
    }
    for i := 3; i*i <= n; i += 2 {
        if n%i == 0 {
            return false
        }
    }
    return true
}

Create a free account to submit solutions, track progress and save problems.

Create account