使用 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.
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP