两个整数之间的 Armstrong 数?
如果将一个整数的每一位数字取出单独立方后求和所得和等于该数本身,则称该整数为 n 阶阿姆斯特朗数,即 abcd... = a3 + b3 + c3 + d3 + ...。
对于一个 3 位阿姆斯特朗数,其每一位数字的立方和等于该数本身。例如:
153 = 13 + 53 + 33 // 153 是一个阿姆斯特朗数。
Input: Enter two numbers(intervals):999 9999 Output: Armstrong numbers between 999 and 9999 are: 1634 8208 9474
说明
1634 = 13+63+33+43 = 1+216+27+64 = 1634
下面实现的方法很简单。我们遍历给定范围内的所有数字。对于每一个数字,我们首先计算其位数。令当前数字的位数为 n。然后我们计算所有数字立方和。如果和等于 I,则打印该数字。
示例
#include <stdio.h>
#include <math.h>
int main() {
int low = 100;
int high = 400;
printf("The amstrong numbers between %d and %d is \n",low,high);
for (int i = low+1; i < high; ++i) {
int x = i;
int n = 0;
while (x != 0) {
x /= 10;
++n;
}
int pow_sum = 0;
x = i;
while (x != 0) {
int digit = x % 10;
pow_sum += pow(digit, n);
x /= 10;
}
if (pow_sum == i)
printf("%d ", i);
}
printf("\n");
return 0;
}
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP