Program to check the given number is perfect number or not in C++. Perfect Number program in c++

Program to check the given number is perfect number or not



 Perfect Number :-                  

    A perfect number that is equal to the addition of  all positive divisors, excluding the number itself.

Example: 

        Consider 6, the divisors of 6 are 1, 2 & 3. Thus, 1 + 2 + 3 = 6. Hence 6 is a Perfect Number.


Code

#include<bits/stdc++.h>
using namespace std;

int main(){

    cout<<"Enter a Number"<<endl;       //Requesting a number
  int n;                                              //To store the number
cin>>n;                                         //Reading the number

int sum=0;                               //To store the sum of divisors

for(int i=1; i<n; i++){             //loop to go from 1 to given number
if(n%i==0){
sum=sum+i;          //if the number is perfect divisor add to sum
}
}

//If the sum matches the original number then it's a perfect number

if(sum==n){
cout<<"It's a Perfect Number "<<endl;
}

//if sum is not equal to original number then it's not a perfect number

else{
cout<<"Not a Perfect Number"<<endl;
}

    return 0;
}


Input

15

Output

Enter a Number
15
Not a Perfect Number


Program to print Perfect numbers from 1 to N.



#include<bits/stdc++.h>
using namespace std;

int main(){
    cout<<"Enter a number"<<endl;                //Requesting a Number
    int n;                                                          //to store entered number
    cin>>n;                                                    //Reading the number
    for(int i=1; i<=n; i++){                      //loop to go from 1 to N
int sum=0;                          //to store sum of divisors
for(int j=1; j<i; j++){               //loop to check divisors
if(i%j==0){
sum=sum+j;            //if divides perfectly add to sum
}
}
        if(sum==i){                        //if sum matches original number print the number
cout<<i<<" ";
        }
        
    }
    return 0;
}

Input

100

Output

Enter a number
100
6 28 

Post a Comment

0 Comments