C Exercise Example 19

100 Classic C Examples

Title:A number is called a "perfect number" if it is exactly equal to the sum of its factors, for example6=1+2+3, please write a program to find all perfect numbers within 1000.

Program analysis:Please refer to:C Practice Example 14。

Example

// Created by www.example.com on 15/11/9. // Copyright © 2015 Example. All rights reserved. // #include <stdio.h> int main() { int i, j, sum; printf("Perfect numbers within 1000 are:\n"); for (i = 1; i <= 1000; i++) { sum = 0; // Reset sum before each loop // Find all proper divisors of i and sum them for (j = 1; j < i; j++) { if (i % j == 0) { sum += j; } } // If the sum equals i itself, it is a perfect number if (sum == i) { printf("%d = 1", i); // All perfect numbers include 1 // Print other factors for (j = 2; j < i; j++) { if (i % j == 0) { printf(" + %d", j); } } printf("\n"); } } return 0; }

The output of the above example is:

6 = 1 + 2 + 3
28 = 1 + 2 + 4 + 7 + 14
496 = 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248

100 Classic C Examples

other extensions