1011: "水仙花数"问题2

Description

输出所有的"水仙花数".所谓"水仙花数"是指这样的一个三位数:其各位数字的立方和等于该数本身。例如:371是一个"水仙花数",371=3^3+7^3+1^3.

Input

Output

输出所有的"水仙花数"(从小到大的顺序输出,每行一个数据)

Sample Input

Sample Output

HINT


均为三位数字
输出所有的"水仙花数"(从小到大的顺序输出,每行一个数据)

#include<iostream>
#include<math.h>
using namespace std;
int main()
{int i,a,b,c;
    for(i=100;i<1000;i++)
    {
        a=i%10;
        b=i/10%10;
        c=i/100;
       if(i==pow(a,3)+pow(b,3)+pow(c,3))
       {cout<<i<<endl;}}
    return 0;
}

pow函数经查阅算法如下:

int pow(int x, int y)
{
    if (y == 1) return x;
    int result = 0;
    int tmp = pow(x, y/2);
    if(y&1 != 0) //奇数位与运算
    {
        result = x * tmp * tmp;
    }
    else
    {
        result = tmp * tmp;
    }

其中if(y&1 != 0) // 奇数位与运算 ,用y的二进制数最后一位与1与运算,用此来判断奇偶。

该函数重复利用计算结果,减少计算次数,缩短时间。例如:x^5=x * x^2 * x^2   其中 x^2= x *  x  。

pow函数原型:

     double pow (      double base,      double exponent );
long double pow ( long double base, long double exponent );
      float pow (       float base,       float exponent );
     double pow (      double base,         int exponent );
long double pow ( long double base,         int exponent );

猜你喜欢

转载自blog.csdn.net/meng1ge/article/details/81103596