您好,欢迎访问一九零五行业门户网

C程序检查强数

给定一个数字'n',我们需要检查给定的数字是否是强数。
强数是指其所有数字的阶乘之和等于数字'n'。阶乘是指将小于该数字的所有数字(包括该数字)相乘的结果,用!(感叹号)表示。例如:4!= 4x3x2x1 = 24。
因此,要确定一个数字是否是强数,我们需要提取数字的每一位,例如数字为145,则我们需要提取1、4和5,然后我们将计算每个数字的阶乘,即1!= 1,4!= 24,5!= 120。
现在我们将1 + 24 + 120相加,得到145,与给定的输入完全相同,因此我们可以说这个数字是强数。
示例input: n = 124output: no it is not a strong numberexplanation: 1! + 2! + 4! = 27 which is not equal to n i.e, 124input: n = 145output: yes it is a strong numberexplanation: 1! + 4! + 5! = 145
下面使用的方法如下来解决问题 −
我们将 −
从个位数开始取每个数字,并找到其阶乘。我们将这些数字的阶乘相加。将结果与原始数字进行比较,如果它们相等,则该数字是强数;否则该数字不是强数。算法startin 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 factorialin 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 checkin 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
"); else printf("no it is not a strong number
"); return 0;}
如果运行上述代码,将生成以下输出 −
yes it is a strong number
以上就是c程序检查强数的详细内容。
其它类似信息

推荐信息