14040: 【原4040】计算阿姆斯特朗数
题目
题目描述
author: 程序设计思想与方法助教组Xinjian Luo 原OJ链接:https://acm.sjtu.edu.cn/OnlineJudge-old/problem/4040
问题描述
编写一个程序,读入两个正整数a和b,其中a<=b, 计算并输出闭区间[a,b]中的阿姆斯特朗数。阿姆斯特数为各个数位上数字的立方和等于其自身的数字,例如:
153 = 1 * 1 * 1 + 5 * 5 * 5 + 3 * 3 * 3 // 153 is an Armstrong number.
12 is not equal to 1 * 1 * 1 + 2 * 2 * 2 // 12 is not an Armstrong number.
输入输出描述
输入
- 输入为两个正整数(在问题描述中记作a和b,程序中请自定变量名),a和b使用1个空格分隔。
输出
- 输出闭区间[a,b]中的所有阿姆斯特朗数。
- 数据之间用换行符分隔。
- 最后的一行输出后面无换行符。
- 如果输入错误,输出提示信息
error
。 - 如果没有找到阿姆斯特朗数,输出提示信息
no
。
程序运行示例1
Sample Input 1
100 400
Sample Output 1
153
370
371
程序运行示例2
Sample Input 2
-6 7
Sample Output 2
error
程序运行示例3
Sample Input 3
12 12
Sample Output 3
no
注意
- 不要显示多余的提示信息,避免输出判定错误。
- 注意判断输入信息是否符合要求。
ligongzzz's solution
#include "iostream"
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) {
cout << "error";
}
else {
for (; a <= b; a++) {
int temp = a;
int sum = 0;
while (temp > 0) {
sum += (temp % 10)*(temp % 10)*(temp % 10);
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;
}
LuminousXLB's solution
// 4040. 计算阿姆斯特朗数
// #421268 正确 / 分数:100 / 时间:2ms / 内存:4444kb
#include <cstdio>
int vol(int n) {
return n * n * n;
}
int main() {
bool found = false;
size_t inf, sup;
scanf("%d %d", &inf, &sup);
if ((inf <= 0) || (sup < inf)) {
printf("error\n");
return 0;
}
for (size_t i = inf; i <= sup; i++) {
size_t tmp = i, sum = 0;
while (tmp > 0) {
unsigned short digit = tmp % 10;
tmp /= 10;
sum += vol(digit);
}
if (i == sum) {
printf("%d\n", i);
found = true;
}
}
if (!found) {
printf("no\n");
}
}
victrid's solution
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int a, b, armstrong;
bool AF = false;
cin >> a >> b;
if (a > b || a <= 0)
{
cout << "error";
return 0;
}
for (int i = a; i <= b; i++)
{
armstrong = 0;
for (int OpNumber = i;OpNumber!=0;)
{
armstrong += pow((OpNumber % 10), 3);
OpNumber /= 10;
}
if (armstrong == i)
{
if(AF)cout<<endl;
cout <<i;
AF = true;
}
}
if (!AF)cout << "no";
return 0;
}