使用函数输出水仙花数 (20 分)

深碍√TFBOYSˉ_ 2023-10-11 16:01 111阅读 0赞

使用函数输出水仙花数 (20 分)

水仙花数是指一个N位正整数(N≥3),它的每个位上的数字的N次幂之和等于它本身。例如:153=13+53+33。 本题要求编写两个函数,一个判断给定整数是否水仙花数,另一个按从小到大的顺序打印出给定区间(m,n)内所有的水仙花数。

函数接口定义:

  1. int narcissistic( int number );
  2. void PrintN( int m, int n );

函数narcissistic判断number是否为水仙花数,是则返回1,否则返回0。

函数PrintN则打印开区间(m, n)内所有的水仙花数,每个数字占一行。题目保证100≤mn≤10000。

裁判测试程序样例:

  1. #include <stdio.h>
  2. int narcissistic( int number );
  3. void PrintN( int m, int n );
  4. int main()
  5. {
  6. int m, n;
  7. scanf("%d %d", &m, &n);
  8. if ( narcissistic(m) ) printf("%d is a narcissistic number\n", m);
  9. PrintN(m, n);
  10. if ( narcissistic(n) ) printf("%d is a narcissistic number\n", n);
  11. return 0;
  12. }
  13. /* 你的代码将被嵌在这里 */

输入样例:

  1. 153 400

输出样例:

  1. 153 is a narcissistic number
  2. 370
  3. 371

分析:本道题目是很有意思的,值得花费时间去研究,这道题目最难的不是做对,有的时候是做对了,但是超时了,所以这道题最难的是我们要发现优化的地方。 比如:求次方的时候,大多数人都会想着用pow(),但是花费了时间,我们可以选用for循环来实现。

但是在优化的过程当中,我相信没有代码十全十美的,有可能我们优化了某一部分,而另一部分的运行时间变长了,这很正常的,修改一部分的代码,另一部分难道不会发生变化吗?所以博友们不要钻牛角尖哦。

作者请求:如果博友们没有在博主这里找到答案,欢迎博友私信我,一般在下午我都在线,可以单独发给博友,我也是一个菜鸟,希望与大家一起进步努力,成长。

代码实现:

  1. int narcissistic(int number)
  2. {
  3. int temp = 0;
  4. int sum = 0;
  5. int count = 0;
  6. temp = number;
  7. do//使用do…while循环编译后生成的代码的长度短于while循环。
  8. {
  9. temp /= 10;
  10. count++;
  11. } while (temp != 0);
  12. temp = number;//temp循环的使用需要重新赋初值
  13. do
  14. {
  15. int a = temp % 10;
  16. int c=1;
  17. for (int i = 0;i < count;i++)
  18. {
  19. c = a * c;//for循环来实现次方相对来说比pow()节约运行时间,乘法运算要比次方运算快的多
  20. }
  21. sum += c;
  22. temp = temp / 10;
  23. }while (temp > 0);
  24. if (sum == number)
  25. return 1;
  26. else
  27. return 0;
  28. }
  29. void PrintN(int m, int n)
  30. {
  31. int i;
  32. for ( i = m + 1;i < n;i++)
  33. {
  34. if (narcissistic(i) == 1)
  35. printf("%d\n", i);
  36. }
  37. }

发表评论

表情:
评论列表 (有 0 条评论,111人围观)

还没有评论,来说两句吧...

相关阅读