basics · intermediate · ~15 min

Is prime?

Bounded loops and the √n trick.

Challenge

Decide whether a number is prime using trial division up to its square root.

Task

Implement int is_prime(unsigned long n) that returns 1 if n is prime and 0 otherwise. No main — the grader calls it.

Input

One unsigned long argument n (n can be 0 up to large values like 7919).

Output

1 if n is prime, 0 if not. By convention 0 and 1 are not prime.

Example

is_prime(2)    ->   1
is_prime(4)    ->   0
is_prime(97)   ->   1
is_prime(100)  ->   0

Edge cases

  • 0 and 1 return 0.
  • 2 is the only even prime.

Rules

  • Only trial-divide up to sqrt(n) (i*i <= n) for an efficient check.

Input format

One unsigned long argument n.

Output format

1 if n is prime, 0 otherwise (0 and 1 are not prime).

Constraints

Trial-divide only up to sqrt(n).

Starter code

int is_prime(unsigned long n) {
    /* TODO */
    return 0;
}

Common mistakes

Treating 0 or 1 as prime; failing to handle 2 as an even prime; looping all the way to n instead of stopping at sqrt(n) (i*i <= n).

Edge cases to handle

n <= 1 (neither prime nor composite; return 0/false), n = 2 (the only even prime), n = 3, large primes, and perfect squares like 9 or 25.

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.