题目描述
春天是鲜花的季节,水仙花就是其中最迷人的代表,数学上有个水仙花数,他是这样定义的:“水仙花数”是指一个三位数,它的各位数字的立方和等于其本身,比如:153 = 13 + 53 + 33。
现在要求输出所有在 m 和 n 范围内的水仙花数。
Input
输入数据有多组,每组占一行,包括两个整数 m 和 n (100 <= m <= n <= 999)。
Output
对于每个测试实例,要求输出所有在给定范围内的水仙花数,就是说,输出的水仙花数必须大于等于m,并且小于等于n,如果有多个,则要求从小到大排列在一行内输出,之间用一个空格隔开;如果给定的范围内不存在水仙花数,则输出no。
每个测试实例的输出占一行。
Sample Input
100 120
300 380
Sample Output
no
370 371
思路
模拟题目的操作即可。根据题目描述,水仙花数是指一个三位数,它的各位数字的立方和等于其本身。
C语言代码:
#include<stdio.h>
#include<math.h>
int check(int i)
{
int x = i;
int x1 = x % 10;
x = x / 10;
int x2 = x % 10;
x = x / 10;
int x3 = x % 10;
if((x1 * x1 * x1 + x2 * x2 * x2 + x3 * x3 * x3) == i) return 1;
else return 0;
}
int main()
{
int m, n;
while(~scanf("%d %d", &m, &n))
{
int flag = 1;
int cnt = 0;
for(int i = m; i <= n; i++)
{
if(check(i))
{
cnt++;
if(flag)
{
flag--;
printf("%d", i);
}else printf(" %d", i);
}
}
if(cnt == 0) printf("no\n");
else printf("\n");
}
return 0;
}
C++代码:
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false); //加速读入
int m, n, cnt;
while(cin >> m >> n)
{
cnt = 0;
for(int i = m; i <= n; i++)
{
int a = i / 100; //百位
int b = i / 10 % 10;//十位
int c = i % 10; //个位
if(i == a * a * a + b * b * b + c * c * c)
{
if(cnt == 0) cout << i;
else cout << " " << i;
cnt++;
}
}
if(cnt == 0) cout << "no";
cout << endl;
}
return 0;
}
下面这一句的功能是加速读入数据,不写也行。
ios::sync_with_stdio(false);
其实水仙花数一共就4个:153,370,371,407。
因此我们还可以这样写:
#include<iostream>
using namespace std;
int main()
{
int m, n, cnt = 0;
while(scanf("%d%d", &m, &n) != EOF)
{
for(int i = m; i <= n; i++)
if(i == 153 || i == 370 || i == 371 || i == 407)
{
if(cnt == 0)
{
printf("%d", i);
cnt++;
}
else if(cnt > 0) printf(" %d", i);
}
cnt == 0 ? printf("no\n") : printf("\n");
cnt = 0;
}
return 0;
}
没有C语言基础的同学们,可以先学习一下C语言语法,我会整理好,后面发出来
我已经写好了,可以去C语言程序设计专栏看第一周的内容。