Check if a given number divides the sum of the factorials of its digits in C++


Suppose, we have an integer, we have to find if the number divides the sum of the factorial of its digits. Suppose a number is 19, the sum of factorial of digits is (1! + 9!) = 362881, this is divisible by 19.

To solve this, we will take the number, then calculate factorial of each digit and add the sum, if the sum is divisible by the number itself, then return true, otherwise false.

Example

#include <iostream>
using namespace std;
int factorial(int n){
   if(n == 1 || n == 0)
      return 1;
   return factorial(n - 1) * n;
}
bool isDigitsFactDivByNumber(int num){
   int temp = num;
   int sum = 0;
   while(num){
      int digit = num % 10;
      sum += factorial(digit);
      num /= 10;
   }if(sum%temp == 0){
      return true;
   } return false;
}
int main() {
   int number = 19;
   if (isDigitsFactDivByNumber(number))
      cout << "Yes, the number can divides the sum of factorial of digits.";
   else
      cout << "No, the number can not divides the sum of factorial of digits.";
}

Output

Yes, the number can divides the sum of factorial of digits.

Updated on: 22-Oct-2019

114 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements