Easy Tutorial
❮ C Pointer To An Array C Exercise Example52 ❯

C Exercise Example 19

C Language Classic 100 Examples

Title: A number that is exactly equal to the sum of its factors is called a "perfect number." For example, 6 = 1 + 2 + 3. Program to find all perfect numbers within 1000.

Program Analysis: Please refer to: C Exercise Example 14.

Example

//  Created by www.tutorialpro.org on 15/11/9.
//  Copyright © 2015年 tutorialpro.org. All rights reserved.
//

#include<stdio.h>
#define N 1000
int main()
{
    int i,j,k,n,sum;
    int a[256];
    for(i=2;i<=N;i++)
    {
        sum=a[0]=1;
        k=0;
        for(j=2;j<=(i/2);j++)
        {
            if(i%j==0)
            {
                sum+=j;
                a[++k]=j;
            }

        }
        if(i==sum)
        {
            printf("%d=%d",i,a[0]);
            for(n=1;n<=k;n++)
                printf("+%d",a[n]);
            printf("\n");
        }

    }
    return 0;
}

The above example outputs:

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

C Language Classic 100 Examples

❮ C Pointer To An Array C Exercise Example52 ❯