Write is_prime() that tests divisors only up to √n, and print all primes up to 50.
Solution
main.c
#include <stdbool.h>
#include <stdio.h>
bool is_prime(int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
for (int d = 3; d * d <= n; d += 2) /* only odd divisors up to sqrt(n) */
if (n % d == 0)
return false;
return true;
}
int main(void) {
for (int n = 1; n <= 50; n++)
if (is_prime(n))
printf("%d ", n);
printf("\n");
return 0;
}
Output Verified by compiling and running
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
If n has a divisor larger than √n, it also has one smaller, so checking up to √n is enough. d * d <= n avoids calling sqrt(), and skipping even divisors halves the work.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!