14154: 【原4154】真·阿姆斯特朗数
题目
题目描述
author: 程序设计思想与方法助教组Duke 原OJ链接:https://acm.sjtu.edu.cn/OnlineJudge-old/problem/4154
问题描述
如果一个n位正整数等于其各位数字的n次方之和,则称该数为阿姆斯特朗数
(Armstrong number
)。例如:
1 = 1 // 1 is an Armstrong number.
12 ≠ 1 * 1 + 2 * 2 // 12 is NOT an Armstrong number.
153 = 1 * 1 * 1 + 5 * 5 * 5 + 3 * 3 * 3 // 153 is an Armstrong number.
8208 = 8 ^ 4 + 2 ^ 4 + 0 ^ 4 + 8 ^ 4 // 8208 is an Armstrong number.
93084 = 9 ^ 5 + 3 ^ 5 + 0 ^ 5 + 8 ^ 5 + 4 ^ 5 // 93084 is an Armstrong number.
在作业中,小伙伴们已经完成了3次方阿姆斯特朗数
(也称作水仙花数
)。
不少小伙伴查询后,发现水仙花数不是真·阿姆斯特朗数
,OK,真的来了:
- 编写程序,读入两个整数a和b,计算并输出闭区间[a,b]中的
阿姆斯特朗数
。
输入输出描述
输入
- 输入为两个整数(在问题描述中记作a和b,程序中请自定变量名),a和b使用1个空格分隔。
输出
- 输出闭区间[a,b]中的所有
阿姆斯特朗数
。 - 数据之间用换行符分隔。
- 如果输入错误,输出提示信息
error
。 - 如果没有找到
阿姆斯特朗数
,输出提示信息no
。
数据范围说明
- 本次考试中,
阿姆斯特朗数
限定范围为5位以内正整数,即输入范围为[1, 99999],其他数据均输出error
。
程序运行示例
示例1
Sample Input 1
400 4000
Sample Output 1
407
1634
示例2
Sample Input 2
-6 7
Sample Output 2
error
示例3
Sample Input 3
12 15
Sample Output 3
no
示例4
Sample Input 4
5 200
Sample Output 4
5
6
7
8
9
153
注意
- 不要显示多余的提示信息,避免输出判定错误。
- 注意判断输入信息是否符合要求。
ligongzzz's solution
#include "iostream"
#include "cmath"
using namespace std;
int main() {
int a = 0, b = 0;
int result[10000];
int count = 0;
cin >> a >> b;
if (a > b || a <= 0 || b <= 0 || a > 99999 || b > 99999) {
cout << "error";
}
else {
for (; a <= b; a++) {
//计算位数
int weishu = 0;
int temp0 = a;
for (; temp0 != 0;) {
temp0 /= 10;
weishu++;
}
int temp = a;
int sum = 0;
while (temp > 0) {
sum += int(pow(double(temp % 10), double(weishu)));
temp = (temp - (temp % 10)) / 10;
}
if (sum == a) {
result[count++] = a;
}
}
//输出
if (count == 0)
cout << "no";
else {
cout << result[0];
for (int i = 1; i < count; i++)
cout << endl << result[i];
}
}
return 0;
}