In: Computer Science
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 too 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).
2. Make sure the number is positive (at least 1).
3. Go from 1 to to the upper limit and print all numbers that are perfect.
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
In case of any query, do comment. Please rate your answer. Thanks
Please use below code:
#include <iostream>
using namespace std;
int main()
{
int upperValue = 0, sumOfDivisors=0;
cout<<"Welcome to the locate perfect numbers program..."<<endl;
cout<<"What is the upper value? " ;
cin>> upperValue;
//if upper value not in range, ask again to take input
while(upperValue <= 0)
{
cout<<"What is the upper value? (must be an integer > 0) ";
cin>> upperValue;
}
//Print the perfect numbers
cout<<"The following are perfect numbers..."<<endl;
//iterate through 1 to uppervalue
for (int number = 1; number <= upperValue; number++) {
//reset the sum of divisors to 0
sumOfDivisors =0;
for(int i=1; i<number; i++)
{
//find divisor of the number and add it to sumOfDivisors
if(number % i == 0)
{
sumOfDivisors = sumOfDivisors + i;
}
}
//after all divisors check if sumOfDivisors is equal to number then print the number
if(sumOfDivisors == number)
cout<< number<< endl;
}
return 0;
}
===================screen shot of the code=========================
Output: