C Exercise 19
100 Classic C Language Examples
**Problem:** If a number happens to equal the sum of its factors, it is called a "perfect number". For example, 6=1+2+3. Write a program to find all perfect numbers within 1000.
**Analysis:** Please refer to:C Exercise 14.
Example
// Created by www.runoob.com on 15/11/9.
// Copyright (c) 2015 Runoob Tutorial. All rights reserved.
//
#include
<
stdio.h
int
main
(
)
{
int
i
,
j
,
sum;
printf
(
"
The perfect numbers within 1000 are:
\
n
"
)
;
for
(
i
=
1
;
i
<=
1000
;
i
++
)
{
sum
=
0
;
// Reset sum before each loop
// Find all proper factors 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 the 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