Put a test in a function, and use it many times.
What to build
A function that returns 1 for true and 0 for false.
Requirements
- Write
int is_prime(int n). - For each query, print
primeornot prime.
Input
The first line has q. The next line has q whole numbers.
Output
One line per number.
Constraints
q is from 1 to 100. Each number is from 0 to 1000000.
Example
Input:
3
2 4 7
Output:
prime
not prime
prime
Why it works
C has no special true or false in older code, so a function returns 0 or 1, and if (is_prime(n)) reads naturally.
Examples
Example 1 · Input
3 2 4 7
Expected output
prime not prime prime
Example 2 · Input
2 0 1
Expected output
not prime not prime
Hints
Hint 1
Write int is_prime(int n), returning 1 or 0.
Hint 2
Numbers below 2 are not prime.
Hint 3
Test divisors while d * d <= n.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
int is_prime(int n) {
if (n < 2) {
return 0;
}
for (int d = 2; d * d <= n; d++) {
if (n % d == 0) {
return 0;
}
}
return 1;
}
int main(void) {
int q;
scanf("%d", &q);
for (int i = 0; i < q; i++) {
int n;
scanf("%d", &n);
printf(is_prime(n) ? "prime\n" : "not prime\n");
}
return 0;
}