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.
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!