博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
求出0〜999之间的所有“水仙花数”并输出。
阅读量:4116 次
发布时间:2019-05-25

本文共 794 字,大约阅读时间需要 2 分钟。



水仙花数是指一个 n 位数 ,它的每个位上的数字的 n 次幂之和等于它本身。在数论中,水仙花数(Narcissistic number)也称为自恋数、自幂数、阿姆斯壮数或阿姆斯特朗数(Armstrong number)。

例如153、370、371及407就是三位数的水仙花数,其各个数之立方和等于该数:
153 = 1^3 + 5^3 + 3^3。
370 = 3^3 + 7^3 + 0^3。
371 = 3^3 + 7^3 + 1^3。
407 = 4^3 + 0^3 + 7^3。

#include
#include
#include
int isWaterFlower(int x){ int n = 0; int sum = 0; int y = x; if (x >=0&&x <=10)//判断是几位数。 { n=1; } else if (x >= 10&&x <=100) { n = 2; } else if (x >= 100&&x < 10000) { n = 3; } else { printf("error"); return 0; } while (x) { sum += pow(x % 10, n); x = x / 10; } if (y == sum)//一位数字的n次幂的和正好等于这个数本身。 { return 1; } return 0; }int main(){ int i = 0; for (; i < 1000; i++) { if (isWaterFlower(i)) { printf("%d\n", i); } } printf("\n"); system("pause"); return 0;}
输出结果为:
你可能感兴趣的文章
web.py 0.3 新手指南 - RESTful doctesting using app.request
查看>>
web.py 0.3 新手指南 - 使用db.query进行高级数据库查询
查看>>
web.py 0.3 新手指南 - 多数据库使用
查看>>
一步步开发 Spring MVC 应用
查看>>
python: extend (扩展) 与 append (追加) 的差别
查看>>
「译」在 python 中,如果 x 是 list,为什么 x += "ha" 可以运行,而 x = x + "ha" 却抛出异常呢?...
查看>>
浅谈JavaScript的语言特性
查看>>
LeetCode第39题思悟——组合总和(combination-sum)
查看>>
LeetCode第43题思悟——字符串相乘(multiply-strings)
查看>>
LeetCode第44题思悟——通配符匹配(wildcard-matching)
查看>>
LeetCode第45题思悟——跳跃游戏(jump-game-ii)
查看>>
LeetCode第46题思悟——全排列(permutations)
查看>>
LeetCode第47题思悟—— 全排列 II(permutations-ii)
查看>>
LeetCode第48题思悟——旋转图像(rotate-image)
查看>>
驱动力3.0,动力全开~
查看>>
记CSDN访问量10万+
查看>>
Linux下Oracle数据库账户被锁:the account is locked问题的解决
查看>>
记CSDN访问20万+
查看>>
Windows 环境下Webstorm 2020.3 版本在右下角找不到Git分支切换部件的一种解决方法
查看>>
Electron-Vue项目中遇到fs.rm is not a function问题的解决过程
查看>>