C程式判斷給定數字是否為強數


強數是指其各位數字階乘之和等於自身。

示例

  • 123!= 1!+2!+3!

                   =1+2+6 =9

這裡,123 不是強數,因為各位數字階乘之和不等於自身。

  • 145!=1!+4!+5!

            =1+24+120

            =145

這裡,145 是強數,因為各位數字階乘之和等於自身。

我們用來判斷給定數字是否為強數的邏輯如下:

while(n){
   i = 1,fact = 1;
   rem = n % 10;
   while(i <= rem){
      fact = fact * i;
      i++;
   }
   sum = sum + fact;
   n = n / 10;
}
if(sum == temp)
   printf("%d is a strong number
",temp); else    printf("%d is not a strong number
",temp);

程式

以下是判斷給定數字是否為強數的C程式:

#include<stdio.h>
int main(){
   int n,i;
   int fact,rem;
   printf("
Enter a number : ");    scanf("%d",&n);    printf("
");    int sum = 0;    int temp = n;    while(n){       i = 1,fact = 1;       rem = n % 10;       while(i <= rem){          fact = fact * i;          i++;       }       sum = sum + fact;       n = n / 10;    }    if(sum == temp)       printf("%d is a strong number
",temp);    else       printf("%d is not a strong number
",temp);    return 0; }

輸出

執行上述程式後,將產生以下結果:

Run 1:
Enter a number : 145
145 is a strong number
Run 2:
Enter a number : 25
25 is not a strong number

更新於:2023年11月6日

35K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.