C++ Program to check if a number is Multiply Perfect Number

In this post, we will implement a C++ program to check if a number is Multiply Perfect Number.

What’s a Multiply Perfect Number?

First, let us understand what is a Multiply-Perfect Number. A multiply perfect number is a generalization of a perfect number. Let’s say we have a number N for example. It is said to be multiply-perfect if the sum of all its divisors is divisible by the number itself. 

In other words, a number N is a multiply-perfect number if

sigma(N) % N = 0; where sigma(N) represents the sum of divisors of N.

Some of the multiply-perfect numbers are as follows:

1, 6, 28, 120, 496..and so on.

For example, divisors of 120 are 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120. Value of sigma(120) = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 10 + 12 + 15 + 20 + 24 + 30 + 40 + 60 + 120 = 360. Since 360 is divisible by 120, 120 is a multiply-perfect number.

C++ Program to check for Multiply Perfect Number

Next, we will see a C++ program that checks whether a number is a Multiply perfect number or not. 

In the given example program, we find the sum of all divisors of N, and then we check if the sum is divisible by N using the modulo operator. If the sum is divisible then the number N is a multiply-perfect number else it is not.

Have a look at the below C++ code.

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int n = 120;
    int sum = 0;
    
    for(int i=1;i<=sqrt(n);i++)
    {
        if(n%i==0)
        {
            if(n/i == i)
            {
                sum += i;
            }
            else
            {
                sum += i;
                sum += (n/i);
            }
        }
    }
    
    cout << "sum of divisors = " << sum << endl;
    
    if(sum%n==0)
    {
        cout << n << " is a Multiply Perfect Number." << endl;
    }
    else
    {
        cout << n << " is not a Multiply Perfect Number." << endl;
    }
    return 0;
}

Output:

sum of divisors = 360
120 is a Multiply Perfect Number.

Thank you.

Also read: How to check a perfect number using Python

Leave a Reply

Your email address will not be published. Required fields are marked *