BC91. 水仙花数
描述
春天是鲜花的季节,水仙花就是其中最迷人的代表,数学上有个水仙花数,他是这样定义的: “水仙花数”是指一个三位数,它的各位数字的立方和等于其本身,比如:153=1^3+5^3+3^3。 现在要求输出所有在m和n范围内的水仙花数。输入描述
输入数据有多组,每组占一行,包括两个整数m和n(100 ≤ m ≤ n ≤ 999)。输出描述
对于每个测试实例,要求输出所有在给定范围内的水仙花数,就是说,输出的水仙花数必须大于等于m,并且小于等于n,如果有多个,则要求从小到大排列在一行内输出,之间用一个空格隔开; 如果给定的范围内不存在水仙花数,则输出no; 每个测试实例的输出占一行。示例1
输入:
100 120 300 380
输出:
no 370 371
C++ 解法, 执行用时: 1ms, 内存消耗: 220KB, 提交时间: 2017-07-02
#include <stdio.h> #include <stdlib.h> #include <math.h> int main() { int a,b; while(~scanf("%d %d",&a,&b)) { int i=0; i=a; int flag=0; while(i++<=b) { if(pow(i/100,3)+pow((i%100)/10,3)+pow(i%10,3)==i) { flag++; if (flag ==1) printf("%d",i); else if(flag>1) printf(" %d",i); } } if(flag==0) printf("no\n"); else printf("\n"); } return 0; }
Pascal 解法, 执行用时: 1ms, 内存消耗: 256KB, 提交时间: 2018-10-07
var t,i,j,m,n,x,y,z,l:longint; a:array[1..999] of longint; begin for i:=100 to 999 do begin x:=i div 100; y:=i div 10 mod 10; z:=i mod 10; if x*x*x+y*y*y+z*z*z=i then begin inc(t); a[t]:=i; end; end; while not(eof) do begin l:=0; readln(m,n); for i:=1 to t do if (a[i]>=m) and (a[i]<=n) then if l=1 then write(' ',a[i]) else begin write(a[i]); l:=1; end; if l=0 then writeln('no') else writeln; end; end.
Pascal 解法, 执行用时: 1ms, 内存消耗: 256KB, 提交时间: 2018-10-07
var a, b, f: longint; begin while not eof do begin readln(a, b); f := 0; if(153>=a) and (153<=b) then begin write(153); f:=1; end; if(370>=a) and (370<=b) then begin if f=1 then write(' ', 370) else write(370); f:=1; end; if(371>=a) and (371<=b) then begin if f=1 then write(' ', 371) else write(371); f:=1; end; if(407>=a) and (407<=b) then begin if f=1 then write(' ', 407) else write(407); f:=1; end; if f=0 then write('no'); writeln; end; end.
Pascal 解法, 执行用时: 1ms, 内存消耗: 284KB, 提交时间: 2018-03-23
var a,b,f:longint; begin while not eof do begin readln(a,b);f:=0; if(153>=a)and(153<=b)then begin write(153);f:=1;end; if(370>=a)and(370<=b)then begin if f=1 then write(' ',370)else write(370);f:=1;end; if(371>=a)and(371<=b)then begin if f=1 then write(' ',371)else write(371);f:=1;end; if(407>=a)and(407<=b)then begin if f=1 then write(' ',407)else write(407);f:=1;end; if f=0 then write('no');writeln; end; end.
C++ 解法, 执行用时: 1ms, 内存消耗: 368KB, 提交时间: 2017-08-29
//计算水仙花数 #include <iostream> #include <cmath> using namespace std; int Flower(int n); int main() { int m, n, count = 0; while(cin >> m >> n) { for(int i = m; i <= n; i++) { if(Flower(i)) { count++; if(count==1) cout<<Flower(i); if(count>1) cout<<" "<<Flower(i); } } if(count == 0) { cout << "no"; } } return 0; } int Flower(int n) { int a, b, c; a = n/100; b = n/10%10; c = n%10; int sum = pow(a, 3) + pow(b, 3) + pow(c, 3); if(sum == n) { return n; } else { return 0; } }