给定数字“ n”,我们必须检查给定的数字是否为强数。
强数是一个数字,其所有数字的阶乘之和等于数字“ n”。阶乘表示当我们找到该数字以下所有数字的乘积(包括该数字)时,表示为!(感叹号),例如:4!= 4x3x2x1 = 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