# Disarium Number with examples in C++?

C++Server Side ProgrammingProgramming

A number whose sum of its digits powered with its respective position equals to the number itself is called a disarium number.

The noOfDigits(int num) function takes the number and return the number of digits by constantly dividing the number by 10 while there is only ones place left. On each iteration the digits variable is incremented to keep the digits track and is returned once the while loop ends.

int noOfDigits(int num){
int digits = 0;
int temp = num;
while (temp){
temp= temp/10;
digits++;
}
return digits;
}

Next, isDisarium(int num) is a Boolean function that takes the number and checks if it’s a Disarium number or not. It takes the rightmost digit by number mod 10 and power it to the digits place in number system. The result by powering the number is then added to the sum. The while loop runs till there are no digits left. If the sum is equal to num then true is returned otherwise it returns false.

isDisarium(int num){
int digits = noOfDigits(num);
int sum = 0;
int temp = num;
while (temp){
int rightDigit = temp%10;
sum = sum + pow(rightDigit, digits--);
temp = temp/10;
}
return (sum == num);
}

## Example

Let us look at the following implementation of checking if a number is disarium number or not.

Live Demo

#include<iostream>
#include<math.h>
using namespace std;
int noOfDigits(int num){
int digits = 0;
int temp = num;
while (temp){
temp= temp/10;
digits++;
}
return digits;
}
bool isDisarium(int num){
int digits = noOfDigits(num);
int sum = 0;
int temp = num;
while (temp){
int rightDigit = temp%10;
sum = sum + pow(rightDigit, digits--);
temp = temp/10;
}
return (sum == num);
}
int main(){
int num = 518;
if( isDisarium(num))
cout <<num<<" is a Disarium Number"<<endl;
else
cout << num<<" is not a Disarium Number"<<endl;
return 0;
}

## Output

The above code will produce the following output −

518 is a Disarium Number
Published on 16-Jan-2021 08:18:17