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\n",temp); else printf("%d is not a strong number\n",temp);
程序
以下是用于查找给定数字是否强的C程序-
#include输出结果int main(){ int n,i; int fact,rem; printf("\nEnter a number : "); scanf("%d",&n); printf("\n"); 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\n",temp); else printf("%d is not a strong number\n",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