首页 > 后端开发 > C++ > 正文

C程序检查强数

WBOY
发布: 2023-09-07 09:09:12
转载
1101人浏览过

c程序检查强数

给定一个数字'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</p><p>");
   else
      printf("no it is not a strong number</p><p>");
   return 0;
}
登录后复制

如果运行上述代码,将生成以下输出 −

Yes it is a strong number
登录后复制

以上就是C程序检查强数的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
相关标签:
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号