Almost Perfect Number in C++



Almost Perfect Number in C++

Almost Perfect Number is a positive integer n for which the sum of all its positive proper divisors (excluding the number itself ) is equal to n-1. (i.e., one less than the number n). It is also known as the least deficient number or slightly defective number.

A positive proper divisor is a divisor of a number, excluding the number itself. For example, for n = 6; 1, 2, 3 are positive proper divisors but 6 itself is not.

In Mathematics, we say A number n is almost perfect if:

σ(n)-n = n-1

by simplifying it:

σ(n) = 2n-1

where,

σ(n) is the sum of all positive divisors of n

So, in other words, we can also say that an almost perfect number is a positive integer where the sum of all its proper divisors, including the number itself is equal to 2n - 1.

Let's look at some scenarios to understand in better way:

Scenario 1

Input: 32
Output: Yes it is almost perfect number
Explanation: Proper divisors of 32 :  1 , 2, 4, 8, 16, 32  (including the number itself)
Sum of divisors : 1 + 2 + 4 + 8 + 16 + 32 = 63
N = 32  so,  ?(n)=2n?1 -> 63 = 2*32 - 1 which is  63.

Scenario 2

Input: 16
Output: Yes it is almost perfect Explanation: Proper divisors of 16 :  1 , 2, 4, 8, 16 (including the number itself)
Sum of divisors : 1 + 2 + 4 + 8 + 16 = 31
N = 16  so,  ?(n)=2n?1 -> 31 = 2*16 - 1 which is  31.

In this problem, we will define an algorithm to check whether a number is an almost a perfect number or not and then we will implement it in C++.

Algorithm to find Almost Perfect Number

Following is an algorithm to check a given number is almost perfect or not:

  • Step 1 : Declare a variable n (i.e. positive integer)

  • Step 2 : initialize a variable sum_divisors = 0. It will store the sum of divisors of n.

  • Step 3 : Start a loop, iterating from i = 1 to n. If i divides n completely(n % i == 0), add i to the variable sum_divisors.

  • Step 4 : Once the loop ends, check if sum_divisors == (2*n - 1).

  • Step 5 : If it is equal then print YES else print No.

Example

Following is a C++ program to check a number is Almost Perfect number or not:

#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 sum_divisors = 0;
   for (int i = 1; i <= n; i++) {
      if (n % i == 0)

         sum_divisors += i;
   }
   if (sum_divisors == 2 * n - 1)
      cout << "YES";
   else
      cout << "NO";
}

Following is the output of the above program:

Is 16 an almost perfect number ?
YES
Manisha Chand
Manisha Chand

Words That Decode Code

Updated on: 2025-07-31T15:23:45+05:30

228 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements