检查给定数字是否除以C ++中其数字的阶乘和
假设我们有一个整数,我们必须确定数字是否除以其数字的阶乘之和。假设数字为19,则阶乘之和为(1!+9!)=362881,可以除以19。
为了解决这个问题,我们将取数字,然后计算每个数字的阶乘并加和,如果和数可被数字本身整除,则返回true,否则返回false。
示例
#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.";
}输出结果
Yes, the number can divides the sum of factorial of digits.