ZJ17. 水仙花数
描述
春天是鲜花的季节,水仙花就是其中最迷人的代表,数学上有个水仙花数,他是这样定义的:“水仙花数”是指一个三位数,它的各位数字的立方和等于其本身,比如: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 解法, 执行用时: 2ms, 内存消耗: 376KB, 提交时间: 2020-10-10
#include <stdio.h> int main(void){ int SXHnums[4] = {153,370,371,407}; int m, n, left, right; while(scanf("%d %d", &m, &n) != EOF){ for(left = 0; SXHnums[left] < m; left ++ ); for(right = 3; SXHnums[right] > n; right --); if(right < left) printf("no"); else for(;left <= right; left ++){ printf("%d", SXHnums[left]); if( left != right) putchar(' '); } putchar(10); } return 0; }
C 解法, 执行用时: 3ms, 内存消耗: 312KB, 提交时间: 2022-06-28
#include <stdio.h> #include <stdbool.h> bool check(int val) { int v = val, mod, sum = 0; while(v > 0) { mod = v % 10; sum += mod * mod * mod; v = v / 10; } return sum == val; } int main() { int m, n; int begin = 1000, end = 99; int result[100], resultSize = 0, left, right; int tmp[100], tmpSize = 0, k; while(scanf("%d %d", &m, &n) != EOF) { if (n < begin) { left = m; right = begin - 1; begin = left; end = right > end ? right : end; for (int i = left; i <= right; i++) { if (check(i)) { for (k = resultSize - 1; k >= 0; k--) { if (i < result[k]) { result[k+1] = result[k]; } else { result[k+1] = i; break; } } if (k == -1) { result[0] = i; } resultSize++; } } } else if (m > end) { left = end + 1; right = n; end = right; begin = left < begin ? left : begin; for (int i = left; i <= right; i++) { if (check(i)) { for (k = resultSize - 1; k >= 0; k--) { if (i < result[k]) { result[k+1] = result[k]; } else { result[k+1] = i; break; } } if (k == -1) { result[0] = i; } resultSize++; } } } else { right = begin - 1; if (m < begin) { left = m; begin = m; for (int i = left; i <= right; i++) { if (check(i)) { for (k = resultSize - 1; k >= 0; k--) { if (i < result[k]) { result[k+1] = result[k]; } else { result[k+1] = i; break; } } if (k == -1) { result[0] = i; } resultSize++; } } } left = end + 1; if (n > end) { right = n; end = n; for (int i = left; i <= right; i++) { if (check(i)) { for (k = resultSize - 1; k >= 0; k--) { if (i < result[k]) { result[k+1] = result[k]; } else { result[k+1] = i; break; } } if (k == -1) { result[0] = i; } resultSize++; } } } } tmpSize = 0; for (int i = 0; i < resultSize; i++) { if (result[i] >= m && result[i] <= n) { tmp[tmpSize++] = result[i]; } } if (tmpSize == 0) { printf("no\n"); } else { for (int i = 0; i < tmpSize - 1; i++) { printf("%d ", tmp[i]); } printf("%d\n", tmp[tmpSize-1]); } } return 0; }