is_prime Function
Completed
Write int is_prime(int n) returning 1 or 0. Read n numbers and print only the primes.
Input
Line 1: n. Line 2: n integers.
Output
The primes on one line.
Example
Input
9 1 2 3 4 5 9 11 15 17
Output
2 3 5 11 17
Editor
C
Hints
Return 0 as soon as a divisor is found.
Solution explanation
C traditionally uses int 1/0 as true/false.
Show solution
#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() {
int n, x, first = 1;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &x);
if (is_prime(x)) {
if (!first) printf(" ");
printf("%d", x);
first = 0;
}
}
printf("\n");
return 0;
}