Question #49713

Write a program that:
Prompts the user to enter a positive integer N.
Calls the user-defined function isPerfect( ) which checks if N is perfect or not. A number is perfect if the sum of its divisors other than the number itself. For example 28 is perfect since 28 = 1 + 2 + 4 + 7 + 14, while 8 is not perfect since 8 ≠ 1+ 2 + 4
Prints a message.

Expert's answer

#include <iostream>

using namespace std;

int sum_of_divisors(int n) {

int sum = 0;

for (int i = 1; i < n; ++i) {

if (n % i == 0) sum += i;

}

return sum;

}

int main() {

int user_number=0;

cout<<"PLease input number ";

cin>>user_number;

cout<<sum_of_divisors(user_number)<<endl;

if ( user_number - sum_of_divisors(user_number)==0) {cout<<"Number is perfect";}

else {cout<<"Number is not perfect";};

return 0;

}

using namespace std;

int sum_of_divisors(int n) {

int sum = 0;

for (int i = 1; i < n; ++i) {

if (n % i == 0) sum += i;

}

return sum;

}

int main() {

int user_number=0;

cout<<"PLease input number ";

cin>>user_number;

cout<<sum_of_divisors(user_number)<<endl;

if ( user_number - sum_of_divisors(user_number)==0) {cout<<"Number is perfect";}

else {cout<<"Number is not perfect";};

return 0;

}

``

## Comments

## Leave a comment