basics · intermediate · ~15 min
Bounded loops and the √n trick.
Decide whether a number is prime using trial division up to its square root.
Implement int is_prime(unsigned long n) that returns 1 if n is prime and 0 otherwise. No main — the grader calls it.
One unsigned long argument n (n can be 0 up to large values like 7919).
1 if n is prime, 0 if not. By convention 0 and 1 are not prime.
is_prime(2) -> 1
is_prime(4) -> 0
is_prime(97) -> 1
is_prime(100) -> 0
0 and 1 return 0.2 is the only even prime.i*i <= n) for an efficient check.One unsigned long argument n.
1 if n is prime, 0 otherwise (0 and 1 are not prime).
Trial-divide only up to sqrt(n).
int is_prime(unsigned long n) {
/* TODO */
return 0;
}
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).
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.