LearnFrenzy
Sign in Take a free test

C Loops · Loop Programs · Question 2

Perfect numbers up to 10000 in C Solution, output & explanation

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

Print every perfect number (equal to the sum of its proper divisors) up to 10000, testing divisors only up to √n.

Solution
main.c
#include <stdio.h>

int main(void) {
    for (int n = 2; n <= 10000; n++) {
        int sum = 1;                            /* 1 divides every n */
        for (int d = 2; d * d <= n; d++)
            if (n % d == 0) {
                sum += d;
                if (d != n / d)
                    sum += n / d;               /* the paired divisor */
            }
        if (sum == n)
            printf("%d ", n);
    }
    printf("\n");
    return 0;
}

Output Verified by compiling and running

6 28 496 8128

Divisors come in pairs (d, n/d), so the inner loop stops at √n and adds both – about 100 steps for n = 10000 instead of 10000. 28 = 1 + 2 + 4 + 7 + 14.

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