C程序 查找1-1000之间阿姆斯特朗数字
一个有n个数字的正整数在以下情况下被称为阶数为n的阿姆斯特朗数(阶数是数字的数量):
**xyz… = pow(x,n) + pow(y,n) + pow(z,n) + ….**
在这里,我们将建立一个C程序来打印1到1000之间的阿姆斯特朗数字
输入:
lowerlimit = 1
higherlimit = 1000
输出:
1 2 3 4 5 6 7 8 9 153 370 371 407
示例:
// C Program to Display Armstrong
// numbers between 1 to 1000
#include <math.h>
#include <stdio.h>
int power(int x, unsigned int y)
{
int res = 1; // Initialize result
while (y > 0) {
// If y is odd, multiply
// x with result
if (y & 1)
res = res * x;
// y must be even now
y = y >> 1; // y = y/2
x = x * x; // Change x to x^2
}
return res;
}
int main()
{
printf("Armstrong Numbers between 1-1000 are:\n");
for (int i = 1; i < 1000; ++i) {
int x = i;
int n = 0;
// number of digits calculation
while (x != 0) {
x /= 10;
++n;
}
int powersum = 0;
x = i;
// finding the sum of nth
// power of its digits
while (x != 0) {
int digit = x % 10;
powersum += power(digit, n);
x /= 10;
}
// checking if the obtained
// number is armstrong or not
if (powersum == i)
// printing the result
printf("%d ", i);
}
printf("\n");
return 0;
}
输出
Armstrong Numbers between 1-1000 are:
1 2 3 4 5 6 7 8 9 153 370 371 407