与えられた数が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.
-
C指定された数値の桁を1つのステートメントで合計するプログラム
このセクションでは、複数のステートメントを記述せずに桁の合計を見つける方法を説明します。言い換えれば、1つのステートメントで数字の合計を見つけることができます。 ご存知のように、桁の合計を求めるには、数値を10で割った後の余りを取り、最後の桁を切り取り、数値が0になるまで何度も10で除算します。 これらのタスクを1つのステートメントで実行するには、forループを使用できます。ご存知のとおり、forループには3つの異なるセクションがあります。この場合、初期化フェーズでは何もしていません。次に、条件チェックフェーズでは、数値が0より大きいかどうかをチェックしています。インクリメントデクリメント
-
指定された数値の桁を合計するC++プログラム
これは、C++言語で桁の合計を計算する例です。 例 #include<iostream> using namespace std; int main() { int x, s = 0; cout << "Enter the number : "; cin >> x; while (x != 0) { s = s + x % 10; x = x / 10;