Answer to Question #262536 in C++ for kashan

Question #262536

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.


1
Expert's answer
2021-11-07T14:49:14-0500
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS