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;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.