求水仙花數

題目:
水仙花數是一個十進制數的各個位的三次方之和等於其本身。
ifFlower()函數用來判斷該數是不是水仙花數。
這個程序是輸入兩個整數m, n.
打印出m n之間的水仙花數,如果沒有,就輸出no

#include <iostream>
#include <vector>

using namespace std;

bool isFlower(int num)
{
    bool flag = false;
    int sum = 0;
    int a = num;
    while(a)
    {
        int temp;
        temp = a %10;
        a = a / 10;
        sum += temp * temp * temp;
    }
    if (sum == num)
        flag = true;
    else
        flag = false;
    return flag;
}
int main(void)
{
    vector<bool> nums(1000, 0);
    for(int i = 100; i < 1000; ++i)
    {
        if (isFlower(i))
        {
            nums[i] = true;
        }
        else
        {
            nums[i] = false;
        }
    }
    int m, n;
    while(cin >> m >> n)
    {
        bool cout_flag = false;
        for (int i = m; i <=n; ++i)
        {
            if (nums[i] == true)
            {
                cout << i << " ";
                cout_flag = true;
            }
        }
        cout << endl;
        if (cout_flag == false)
            cout << "no" << endl;
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章