兩個整數之間的 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