Hello all,
I've got quite a task on my hands. I'm having to write a problem that will calculate and display the first five perfect numbers in C++ for a school assignment. This is a huge number crunching problem, as the perfect numbers are 6, 28, 496, 8126, and a huge 33550336. My program will find the fourth perfect number (8126) and then just doesnt do anything. Right now I'm letting the program go and wait and see if it will come up eventually. Here is my code along with program documentation explaining my mode of thought when writing this. All help is appreciated (this is quite long so bear with me):
Code:
/* The Perfect Numbers:
1. 6
2. 28
3. 496
4. 8128
5. 33550336 */
// Include standard C++ header file
#include <iostream.h>
// Begin program with main() statement of void type
void main()
{
// Declare long integer objects x, divisor, I, and pcontrol
/* Description (DESC) of each:
x will hold the number being tested as perfect number
divisor will hold the sum of the divisors of x
I will hold each divisible being tested
and pcontrol will be the control object to keep the for loop going until 5 perfect numbers
are found */
long x, divisor, I, pcontrol;
// Introduce user to program
cout << "**********************************************" << endl;
cout << "********* Perfect Number Generator ***********" << endl;
cout << "**********************************************" << endl << endl;
cout << "This program will generate the first five perfect numbers." << endl << endl;
// Begin initial for statement to generate perfect numbers
/* DESC: x is set to 1, pcontrol is set to 1. We want the for loop to continue
until pcontrol (representing the perfect numbers accounted for reaches five and then end
the loop */
for (x = 1, pcontrol = 1; pcontrol <= 5; x++)
{
// Begin nested for statement to compute sum of divisor
/* DESC: I is set to one, while the divisor is set to 0, this allows unique number
testing after each termination of the loop to rejoin back at these values with the new number
for x. Continue doing this specific for loop until I <= x, and increment I after each iteration */
for (I = 1, divisor = 0; I <= x; I++)
{
// Begin an if statement to test if I divides x, if it does not, it will continue to next
// iteration. If it does, add I to the sum of the divisors of x.
if (x%I == 0)
{
divisor += I;
}
// End if
}
// End for
// Begin an if statement to test if the divisor is equal to 2 times x, and if it is
// its a perfect number, else continue on with the loop and test the next x number
if (divisor == 2 * x)
{
cout << "The number " << x << " is a perfect number." << endl;
pcontrol++;
}
// End if
}
// End for
cout << "Thank you for your patience." << endl;
cin.get();
}
// End main
Thank you very much for your assistance
I should also mention that use of for loops is required in this assignment as we are covering for loops this week