/* ************************************************************************** * Program name : 033_Perfect_number (Version 1.00) * * Author : Duck Wong * * Language : C / C++ * * Compiler : Boodshed Dec-C++ compiler Ver 3.95 * * Computer : PII350 * * O/S : Windows 98 * ************************************************************************** * Version 1.00 : 2000/06/13 - first version * ************************************************************************** * Description : (a) Display information * * (b) Input the lower and upper limits * * (c) Find all perfect number within the range * * (e) Try again ? * ************************************************************************** */ #include #include #include void findperfect(int Lower, int Upper) { int Index_1,Index_2, Count, Sum; char Status; Count = 0; // Note (1) for (Index_1=Lower; Index_1<=Upper; Index_1++) { Sum = 0; // Note (2) for (Index_2=1; Index_2<=floor(sqrt(Index_1)); Index_2++) if ((Index_1 % Index_2)== 0) { Sum += Index_2; if ((Index_2*Index_2) != Index_1) Sum += (Index_1/Index_2); } if (Sum==2*Index_1) { Count++; cout << Index_1 << "\t"; } } cout << "\nThere are " << Count << " perfect numbers in the range."; } int main() { // part 1 : Declaration int Upper, Lower; char Again; // part 2 : Display information cout << "\n Perfect Number\n" << "\nAn integer number is said to be a perfect number if its factors," << "\nincluding 1 but not the number itself, sum to the number.\n" << "\nExample (a) : 6 = 1x6 or 2x3 where 1+2+3 = 6" << "\n (b) : 28 = 1x28, 2x14 or 4x7 where 1+2+14+4+7 = 28\n"; do { // part 3 : input two integer numbers do { cout << "\nThis program can find all perfect numbers within" << "\na range of integer numbers.\n" << "\nPlease enter the lower and upper limits : "; cin >> Lower >> Upper; } while (Lower<=0 || Upper<=0 || Upper < Lower ); // part 4 : Call the function to find all the perfect numbers cout << "\nThe perfect numbers are : \n"; findperfect(Lower,Upper); cout << "\n"; // part 5 : Try another range ? cout << "\a\n\nTry another range (Y/N) : "; cin >> Again; } while (Again=='Y' || Again=='y'); cout << "\n\n" << endl; system("PAUSE"); return 0; } /* Notes (1) The variable "Count" is used to count the number of perfect number in the range. The value of Count is set to zero each time before checking the numbers in the range. (2) The variable "Sum" is used to sum all the factors of the number include the number itself. */