Cプログラミング
 Computer >> コンピューター >  >> プログラミング >> Cプログラミング

ストロングナンバーをチェックするCプログラム


数字「n」が与えられた場合、与えられた数字が強い数字であるかどうかを確認する必要があります。

強い数とは、すべての桁の階乗の合計が数「n」に等しい数です。階乗は、その数を含むその数より下のすべての数の積を見つけ、!で表される場合を意味します。 (感嘆符)、例:4! =4x​​3x2x1=24。

したがって、その強い数であるかどうかを見つけるには、数が145であるように、数のすべての桁を選択する必要があります。次に、1、4、および5を選択する必要があります。これで、各数の階乗、つまり1が見つかります。 =1、4! =24、5! =120。

ここで、1 + 24 + 120を合計すると、145が得られます。これは、指定された入力とまったく同じです。したがって、この数値は強い数値であると言えます。

Input: n = 124
Output: No it is not a strong number
Explanation: 1! + 2! + 4! = 27 which is not equal to n i.e, 124
Input: n = 145
Output: Yes it is a strong number
Explanation: 1! + 4! + 5! = 145

問題を解決するために以下で使用されるアプローチは次のとおりです

-

  • 単位の場所から始めて各桁を取り、その階乗を見つけます。
  • 各数値の階乗を追加します。
  • 結果を元の数値と比較します。それらが等しい場合、数値は強い数値です。そうでなければ、その数は強い数ではありません。

アルゴリズム

START
In Function int factorial(int r)
   Step1 -> Initialize int fact and set as 1
   Step2-> Loop while r>1
      Set fact as fact * r
      Decremnet r by 1
   End Loop
   Step 3-> Return fact
   End Function factorial
In Function int check(int n)
   Step 1-> Initialize int temp, rem and result, set result as 0
   Step 2-> Set temp as n
   Step 3-> Loop while temp
      Set rem as temp % 10
      Set result as result + factorial(rem)
      Set temp as temp/10
   End loop
   Step 4-> If result == n then,
      Return 1
   Step 5-> Else
   Return 0
   End function check
In main(int argc, char const *argv[])
   Step 1-> Initialise and set n as 145
   Step 2->If check(n) is valid then,
      Print "Yes it is a strong number”
   Step 3-> Else
      Print "no it is not a strong number”
STOP

#include <stdio.h>
int factorial(int r) {
   int fact = 1;
   while(r>1) {
      fact = fact * r;
      r--;
   }
   return fact;
}
int check(int n) {
   int temp, rem, result = 0;
   temp = n;
   while(temp) {
      rem = temp % 10;
      result = result + factorial(rem);
      temp = temp/10;
   }
   if (result == n)
      return 1;
   else
      return 0;
}
int main(int argc, char const *argv[]) {
   int n = 145;
   if (check(n))
      printf("Yes it is a strong number\n");
   else
      printf("no it is not a strong number\n");
   return 0;
}

上記のコードを実行すると、次の出力が生成されます-

Yes it is a strong number

  1. 素数をチェックするPythonプログラム

    この記事では、以下に示す問題ステートメントの解決策について学習します。 問題の説明 −数が与えられているので、与えられた数が素数であるかどうかを確認する必要があります。 1より大きい特定の正の数で、1以外の要素はなく、その数自体は素数と呼ばれます。 2、3、5、7などは他の要素がないため素数です。 以下のこのプログラムでは、素数または非素数の性質について番号がチェックされます。 1以下の数は素数とは言えません。したがって、数値が1より大きい場合にのみ反復します。 ここで、その数が2から(num-1 // 2)の範囲の任意の数で正確に割り切れるかどうかを確認します。指定された範囲内に何ら

  2. アームストロング数をチェックするPythonプログラム

    この記事では、特定の問題ステートメントを解決するための解決策とアプローチについて学習します。 問題の説明 整数nが与えられた場合、与えられた整数がアームストロング数であることを確認する必要があります。 正の整数は、次の場合、n次のアームストロング数と呼ばれます abcd... = a^n + b^n + c^n + d^n + … ここでは、3桁のアームストロング数、つまり3桁のブルートフォースアプローチについて説明します。 オーダーnのアームストロング番号を確認するには、3を行番号7の対応するオーダー値に置き換える必要があります。 それでは、実装を見てみましょう- 例