水仙花数C语言代码优化

版权声明:ahoj https://blog.csdn.net/Hanoi_ahoj/article/details/82915314

原文地址

题目:求出0~999之间的所有“水仙花数”并输出。“水仙花数”是指一个三位数,其各位数字的立方和确好等于该数本身,如;153=13+53+3^3,则153是一个“水仙花数”。

在数论中,水仙花数(Narcissistic number)也称为自恋数、自幂数、阿姆斯壮数或阿姆斯特朗数(Armstrong number),是指一N位数,其各个数之N次方和等于该数。

例如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。

1.很挫的代码

for (int i=100; i<=999; i++)
{
     int t = pow(i%10,3) + pow(i/10%10,3) + pow(i/100,3);
     if (t == i)
     {
          printf("%d ",i);
     }
}

我写的这段代码真的是很挫很挫,如果要求0~9999999之间的水仙花数呢?难道有多少位就写多少个pow嘛?

2.稍加修改后的代码

for (int i=0; i<=999; i++)
{
    // 1.确定位数
    int cnt = 1;
    int sum = 0;
    int temp = i;
    while(temp > 9)
    {
        cnt++;
        temp /= 10;
    }
    // 2.计算次方和
    temp  = i;
    while(temp)
    {
        sum += pow(temp%10,cnt);
        temp /= 10;
    }
    // 3.判断打印
    if (sum == i)
    {
        printf("%d,",i);
    }
}

这下就思路清晰了很多,虽然稍微长了点。

3.反思

国庆开始啦,今天开始读《高质量C/C++编程指南》,今后code需要养成良好的习惯。

继续学习。

原文地址

猜你喜欢

转载自blog.csdn.net/Hanoi_ahoj/article/details/82915314