Write a C++ program to print all the perfect numbers below a certain given number. A perfect number is a number that that is equal to the sum of it's divisors other than itself . For example, 6 and 28 are all perfect numbers.
6 = ( 1+2 +3)
28 = (1+2+4+7+14)
Make sure your program conforms to the following
requirements:
1. Accept the upper limit from the user (as an integer). (5
points)
2. Make sure the number is positive (at least 1). (5 points).
3. Go from 1 to to the upper limit and print all numbers that are
perfect. (35 points)
4. Add comments wherever necessary. (5 points)
Sample Runs:
NOTE: not all possible runs are shown below.
Sample Run 1
Welcome to the locate perfect numbers program...
What is the upper value?30
The following are perfect numbers...
6
28
Process finished with exit code 0
Sample Run 2
Welcome to the locate perfect numbers program...
What is the upper value?-8
What is the upper value? (must be an integer >
0)0
What is the upper value? (must be an integer >
0)500
The following are perfect numbers...
6
28
496
General Requirements:
1. No global variables (variables outside of main() )
2.Please try and restrict yourself to input/output statements, variables, selection statements and loops. Using any other concept (like functions or arrays) will result in loss of points.
3. All input and output must be done with streams, using the library iostream
4. You may only use the cmath, iostream, and iomanip libraries (you do not need any others for these tasks)
5. NO C style printing is permitted. (Aka, don’t use printf). Use cout if you need to print to the screen.
6. When you write source code, it should be readable and well-documented (comments).
// do comment if any problem arises
//code
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int upper_value;
// welcome message
cout << "Welcome to the locate perfect numbers program...\n";
cout << "What is the upper value?";
// read upper value from user
cin >> upper_value;
// read upper value till user enters positive number
while (upper_value <= 0)
{
cout << "What is the upper value? (must be an integer > 0)";
cin >> upper_value;
}
cout << "The following are perfect numbers...\n";
for (int number = 1; number <= upper_value; number++)
{
int sum = 0;
// calculate sum of its devisors
for (int j = 1; j < number; j++)
{
if (number % j == 0)
sum += j;
}
// if sum is equal to number itself then number is perfect
if (sum == number)
cout << number << endl;
}
}
Output:
Get Answers For Free
Most questions answered within 1 hours.