Almost Perfect Number in C++


Almost Perfect Number also known the least deficient number or slightly defective number is a number in which the sum of all divisors ( adding 1 and the number itself ) should be equal to 2n-1.

In this problem, we will define an algorithm to check whether a number is an almost a perfect number or not.

Let's take an example to understand the concept better,

Input : 16
Output : yes
Explanation :
Divisors of 16 are 1, 2, 4, 8, 16.
Sum = 1 + 2 + 4 + 8 + 16 = 31
n = 16 ; 2n-1 = 2*16 - 1 = 31

Input : 12
Output : No
Explanation :
Divisors of 12 are 1, 2, 3, 4, 6, 12.
Sum = 1+2+3+4+6+12 = 26
n = 12 ; 2n-1 = 2*12 - 1 = 23

Now, the problem to check whether the given number is an almost perfect number or not is solved using the logic of almost perfect number i.e. if the sum of all divisors of the number is equal to 2n -1.

Algorithm

Step 1 : Calculate the sum of all divisors of the number.
Step 2 : Calculate the value of val = 2n-1.
Step 3 : if sum == val -> print “YES”
Step 4 : else print “NO”

Example

 Live Demo

#include <iostream>
using namespace std;
void almostPerfectNumber(int n) ;
int main(){
   int n = 16;
   cout<<"Is "<<n<<" an almost perfect number ?\n";
   almostPerfectNumber(n) ;
}
void almostPerfectNumber(int n){
   int divisors = 0;
   for (int i = 1; i <= n; i++) {
      if (n % i == 0)
         divisors += i;
   }
   if (divisors == 2 * n - 1)
      cout<<"YES";
   else
   cout<<"NO";
}

Output

Is 16 an almost perfect number ?
YES

Updated on: 16-Oct-2019

126 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements