Learn-c-by-examples-armstrong-number-program-in-c

提供:Dev Guides
移動先:案内検索

Cのアームストロング番号プログラム

アームストロング数は、個々の数字の立方体の合計に等しい数です。 たとえば、153は次のようなアームストロング番号です-

153 = (1)3 + (5)3 + (3)3
153 = 1 + 125 + 27
153 = 153

アルゴリズム

このプログラムのアルゴリズムは非常に簡単です-

START
   Step 1 → Take integer variable Arms
   Step 2 → Assign value to the variable
   Step 3 → Split all digits of Arms
   Step 4 → Find cube-value of each digits
   Step 5 → Add all cube-values together
   Step 6 → Save the output to Sum variable
   Step 7 → If Sum equals to Arms print Armstrong Number
   Step 8 → If Sum not equals to Arms print Not Armstrong Number
STOP

疑似コード

次のように上記のアルゴリズムの擬似コードを作成できます-

procedure armstrong : number

   check = number
   rem   = 0

   WHILE check IS NOT 0
      rem ← check modulo 10
      sum ← sum + (rem)3
      divide check by 10
   END WHILE

   IF sum equals to number
      PRINT armstrong
   ELSE
      PRINT not an armstrong
   END IF

end procedure

実装

このアルゴリズムの実装を以下に示します。 あなたは `+ arms +`変数の値を変更し、プログラムを実行して確認することができます-

#include <stdio.h>

int main() {
   int arms = 153;
   int check, rem, sum = 0;

   check = arms;

   while(check != 0) {
      rem = check % 10;
      sum = sum + (rem *rem* rem);
      check = check/10;
   }

   if(sum == arms)
      printf("%d is an armstrong number.", arms);
   else
      printf("%d is not an armstrong number.", arms);

   return 0;
}

出力

プログラムの出力は次のようになります-

153 is an armstrong number.