Dec 5, 2016

Program: Print first 10 Perfect Number

Program: Find or Print first 10 Perfect Number

Perfect number is a positive number which sum of all positive divisors excluding that number.
For example: 6 is perfect number as divisor of 6 are 1, 2, 3. Sum of it divisor is 1 + 2 + 3 = 6.

Simple way to do is find divisor of each element and check for perfect number. But it is slow as it take more time.
So there is general way to find perfect number as given in wikipedia, perfect number exist only for even number. It is given by 2p−1(2p − 1) where p is a prime number 
For example for p = 2 : 21(22 − 1) = 6,
similarly for p = 3 : 22(23 − 1) = 28 ...

So in this program we are printing up to 10 perfect number.

#include <iostream>
#include <cmath> //for pow function
using namespace std;

bool isPrime(int n) //check prime number 
{
//this snippet is taken from program: Check given number for Prime Number
 bool flag = true;
 if(n<2)
  flag = false;
 else if(n == 2)
  flag = true;

        else if(n%2 ==0)
              flag = false;
 else{
  for(int i=3;i<n;i+=2){
   if(n%i == 0)
   {
    flag = false;
     break;
   }
  }

 }
       return flag; //return boolean value
}

/*
using above formula we made function which return the perfect number according to given prime number.
*/
unsigned long long getPerfectNumber(int n){ 
    return (pow(2,n-1)*(pow(2,n)-1));
}


int main()
{
    //print for prime number = 2
    cout << getPerfectNumber(2)<<endl;
    for(int i =3,j=1;j<10;i+=2){
        if(isPrime(i)){ //check prime if found then will print perfect number
                cout << getPerfectNumber(i)<<endl;    
j++;
}
    }
  return 0; //https://cplspls.blogspot.com

}

OUTPUT:




For those who want to do by simple way by check each number for perfect number then here is program:-

#include <iostream>
using namespace std;

int main() {
unsigned long long sum;
        int n = 4; //number of perfect number to print
for(int i=2,j=0;j<n;i++){//we start from 2 and start checking each number 
sum = 0;
for(int j=1;j<i;j++){ //find divisor
if(i%j == 0)
sum+=j; //add divisor
}
if(sum == i){ //compare sum with number
cout << sum<<endl;
j++;
}
}
return 0;
}

Above program sure look small as compare to above one but time taken to print 10 elements will take a lot of time and memory while first code will give answer within few seconds.

0 comments:

Post a Comment