/* * ----------------------------------------------------- * CS2S03/SE2S03, September 2011 * Assignment 1, Question 2 * File: PE0107.cpp * ----------------------------------------------------- * This program generates and displays the list of * perfect numbers in the range of 1 to 9999. * ----------------------------------------------------- */ #include "genlib.h" #include "simpio.h" #include #include #include /* * Constants * ----------------------------------------------------- * LOWER_LIMIT -- Starting value for the range * UPPER_LIMIT -- Final value for the range */ const int LOWER_LIMIT = 1; const int UPPER_LIMIT = 9999; /* Private function prototypes */ bool IsPerfect(int n); /* Main program */ int main() { for (int i = LOWER_LIMIT; i <= UPPER_LIMIT; i++) { if (IsPerfect(i)) cout << setw(4) << i << " " << "is a perfect number." << endl; } return 0; } /* * Function: IsPerfect * Usage: if (IsPerfect(n)) ... * ------------------------------------------------------------ * This function returns true if integer n is a perfect number, * that is, n equals the sum of its proper divisors. */ bool IsPerfect(int n) { if (n < 1) return false; int sum = 0; //sum of divisors int q; //quotient int ubound = sqrt(n); //upper bound for the potential divisors if (ubound > n - 1) //divisors must be proper ubound = n - 1; for (int divisor = 1; divisor <= ubound; divisor++) { if ((n % divisor == 0)) { //found a divisor sum += divisor; q = n / divisor; if ((q > divisor) && (q < n)) { //the other proper divisor sum += q; } } } return (n == sum); }