C++ 的版本先建立好阿姆斯壯數的對應表,這個阿姆斯壯數可以從 Google 找到,而筆者是用程式跑出來的。
底下是Python版本所用的方法:
首先要知道數字是幾位數,可將數字轉成字串後,在呼叫計算字串長度函數 order = len(str(x)) ,接著就是將每位數的 order 次方加總(s),並檢查是否與原來數字相等
程式碼:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
int main() | |
{ | |
int armstrongNum[] = { | |
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, | |
153, 370, 371, 407, | |
1634, 8208, 9474, | |
54748, 92727, 93084, | |
548834 | |
}; | |
short SIZE = sizeof(armstrongNum) / sizeof(int); | |
bool isArmstrong[1000000]; | |
for(int i = 0; i < SIZE; i++) | |
isArmstrong[armstrongNum[i]] = true; | |
int a, b; | |
while(cin >> a >> b) | |
{ | |
bool hasArm = false; | |
for( ; a <= b; a++ ) | |
{ | |
if(isArmstrong[a]) | |
{ | |
cout << a << " "; | |
hasArm = true; | |
} | |
} | |
if(!hasArm) | |
cout << "none"; | |
cout << endl; | |
} | |
return 0; | |
} |
沒有留言:
張貼留言