Print Friendly and PDF
An integer number is said to be a perfect number if the sum of its factors, including 1 (but not the number itself), is equal to the number. For example, 6 is a perfect number, because 6 = 1 + 2 + 3. Write a function perfect that determines whether parameter number is a perfect number. Use this function in a program that determines and prints all the perfect numbers between 1 and 1000. Print the factors of each perfect number to confirm that the number is indeed perfect. Challenge the power of your computer by testing numbers much larger than 1000.
An integer number is said to be a perfect number if the sum of its factors, including 1 (but not the number itself), is equal to the number. 

For example, 6 is a perfect number, because  6 = 1 + 2 + 3.
 
Write a function perfect that determines whether parameter number is a perfect number. Use this function in a program that determines and prints all the perfect numbers between 1 and 1000.  Print the factors of each perfect number to confirm that the number is indeed perfect. Challenge the power of your computer by testing numbers much larger than 1000.

Solution:

#include <iostream>
using namespace std;
bool perfect( int );
int main()
{
cout << "For the integers from 1 to 1000:\n";
for ( int j = 2; j <= 1000; ++j )
if ( perfect( j ) )
cout << j << " is perfect"<<endl; return 0;
}
bool perfect( int value )
{
int factorSum = 1;
for ( int i = 2; i <= value / 2; ++i )
if ( value % i == 0 )
factorSum += i;
return factorSum == value ? true : false;
}
Output :
For the integers from 1 to 1000:
6 is perfect
28 is perfect
496 is perfect
zubairsaif

Zubair saif

A passionate writer who loves to write on new technology and programming

Post A Comment:

0 comments: