Write a program that prompt the
user to enter a number and determines whether the entered number is a perfect number. Your
program should determine and print all the perfect numbers between 1 and 1000. Print the
divisors of each perfect number to confirm that the number is indeed perfect.
#include <iostream>
#include <iomanip>
using namespace std;
bool isPerfect(int n){
int sumDivisors = 1;
for (int i = 2; i <= n / 2; i++)
{
if ((n % i) == 0){
sumDivisors += i;
}
}
return (sumDivisors == n);
}
int main()
{
int number;
cout<<"Enter number: ";
cin>>number;
if(isPerfect(number)){
cout << "Number is perfect." << endl<< endl;
}else{
cout << "Number is NOT perfect." << endl<< endl;
}
cout << "Perfect numbers between 1 and 1000 (first n, then divisors: " << endl;
for (int n = 1; n <= 1000; n++)
{
if (isPerfect(n))
{
cout << setw(8) << n << " = " << setw(5) << "1";
for (int i = 2; i <= n / 2; i++)
{
if ((n % i) == 0){
cout << " + " << setw(5) << i;
}
}
cout << endl;
}
}
cin>>number;
return 0;
}
Comments
Leave a comment