LearnFrenzy
Sign in Take a free test

Functions · Function Programs · Question 2

Prime number function in C (check up to √n) Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links