Answer to Question #271798 in C++ for Hamda

Question #271798

A perfect number is an integer that is equal to the sum of its factors. For example, 6 is a perfect number as 6 = 3+2+1. Write down a program that takes an integer x as an input and prints all perfect numbers from 1 to x.

1
Expert's answer
2021-11-26T17:44:15-0500
#include<iostream>
using namespace std;
int perfect(int n){
		int sum=0;
	for(int i=1; i<n;i++){
		if(n%i==0){
			sum += i;
		}
	}
	
	if(n==sum){
		return 1;
	}
	else{
		return 0;
	}
}
int main(){
	cout<<"Enter a number:\n";
	int x;
	cin>>x;
	for(int i=1; i<=x; i++){
		if(perfect(i)==1){
			cout<<i<<endl;
		}
	}


	
}

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