(Perfect Numbers) An integer is said to be a perfect number if the sum of its divisors, includ- ing 1 (but not the number itself), is equal to the number. For example, 6 is a perfect number, be- cause 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 divisors 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.

What will be an ideal response?

```
// Determine perfect numbers between 1 and 1000.
// A number is perfect if it is equal to the sum of its factors.
#include
using namespace std;
bool isPerfect( int ); // function prototype
void printSum( int ); // function prototype

int main()
{
cout << "Perfect integers between 1 and 1000:" << endl;

// loop from 2 to 1000
for ( int j = 2; j <= 1000; j++ )
{
// if current integer is perfect
if ( isPerfect( j ) )
printSum( j ); // print it as sum of factors
} // end for

cout << endl;
} // end main

// isPerfect returns true if value is perfect integer,
// i.e., if value is equal to sum of its factors
bool isPerfect( int value )
{
int factorSum = 1; // current sum of factors

// loop through possible factor values
for ( int i = 2; i <= value / 2; i++ )
{
// if i is factor
if ( value % i == 0 )
factorSum += i; // add to sum
} // end for

// return true if value is equal to sum of factors
return factorSum == value;
} // end function isPerfect

// printSum displays value followed by factors in summation form
void printSum( int value )
{
cout << value << " = 1";

// loop through possible factor values
for ( int i = 2; i <= value / 2; i++ )
{
// if i is factor
if ( value % i == 0 )
cout << " + " << i; // display as part of sum
} // end for

cout << endl;
} // end function printSum
```

Computer Science & Information Technology

You might also like to view...

Which of the following formats does NOT support macros?

A) .xlsx B) .xlsb C) .xltm D) .xlsm

Computer Science & Information Technology

It is common to use gettimeofday(2) to measurethe performance of a code segment under study,similar to the following: struct timeval start, end;


If the code segment executes in only 1 microsecond, describe two ways that you can prevent the execution cost of calling gettimeofday from interfering with your measurements

Computer Science & Information Technology