当前位置:   article > 正文

求1到10000的水仙花数(c语言)_求10万以内的水仙花数

求10万以内的水仙花数

题目:

求出0~100000之间的所有“水仙花数”并输出。

“水仙花数”是指一个n位数,其各位数字的n次方之和确好等于该数本身,如:153=1^3+5^3+3^3,则153是一个“水仙花数”。

看到题目我们先要确定要做的几个事情

1.先算出给定的数的位数n

2.算出这个数的各个位上的数的n次方

3.然后将这些数加起来和给定的数相比,如果相同则为水仙花数

一.求给定数的位数

  1. int tem(int i)
  2. {
  3. int count = 1;
  4. while (i / 10)
  5. {
  6. count++;
  7. i = i / 10;
  8. }
  9. return count;
  10. }

二.求各个位上的数的n次方并求和

这里会用到一个函数pow(x,y),其作用是计算x的y次方(需要加上头文件math.h)

  1. int temp = i;//保证给定的i的值不会改变
  2. if (i != 0)
  3. {
  4. while (temp)
  5. {
  6. sum += pow((temp % 10), n);
  7. temp = temp / 10;
  8. }
  9. }
  10. else
  11. {
  12. sum = 1;
  13. }

三.判断是不是水仙花数

  1. if (sum == i)
  2. {
  3. printf("%d\n", i);
  4. }

四.整体代码

  1. #define _CRT_SECURE_NO_WARNINGS 1
  2. #include<stdio.h>
  3. #include<string.h>
  4. #include<math.h>
  5. #include<time.h>
  6. #include<stdlib.h>
  7. int tem(int i)
  8. {
  9. int count = 1;//水仙花数从一位数开始
  10. while (i / 10)
  11. {
  12. count++;
  13. i = i / 10;
  14. }
  15. return count;
  16. }
  17. int main()
  18. {
  19. int i;
  20. for (i = 0; i <= 100000; i++)
  21. {
  22. int sum = 0;
  23. int n = tem(i);//求出位数
  24. int temp = i;//保证给定的i的值不会改变
  25. if (i != 0)
  26. {
  27. while (temp)
  28. {
  29. sum += pow((temp % 10), n);
  30. temp = temp / 10;
  31. }
  32. }
  33. else
  34. {
  35. sum = 1;
  36. }
  37. if (sum == i)
  38. {
  39. printf("%d\n", i);
  40. }
  41. }
  42. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/722168
推荐阅读
相关标签
  

闽ICP备14008679号