/* File: perfect-driver-2.cpp ------------------------------------------------ * Prints the perfect numbers between 1..1000. * Defines sumOfDivisors() and isPerfect() as void-valued functions. * * NOTE: This program has a bug. Insert scaffolding to find it, and * eliminate it. */ #include //for setw, setprecision, fixed, floatfield, showpoint void sumOfDivisors(int n, int& result); void isPerfect(int n, int& result); /* main() ---------------------------------------------------------- */ void main(){ int ans; //answer; result of calling isPerfect() cout << "Perfect numbers 1..1000: "; //generate and test each value of n for(int n = 2; n <= 1000; n++){ //test: is n perfect? isPerfect(n, ans); if(ans) cout << setw(5) << n; } cout << endl << "Exiting.." << endl; } /* sumOfDivisors() ------------------------------------------------- * result is the sum of the proper divisors of n (excluding n) */ void sumOfDivisors(int n, int& result){ int pd = 2, //potential divisor sum = 0; //sum of divisors //sum divisors of n while(pd <= (n / 2)){ if((n % pd) == 0) sum += pd; pd++; } //return results result = sum; } /* isPerfect() ------------------------------------------------- * result is true if n is a perfect number */ void isPerfect(int n, int& result){ int sod; //sum of divisors //assign correct value to sod sumOfDivisors(n, sod); //return result result = (sod == n); }