在此程序中,您將學(xué)習(xí)在Java中顯示兩個(gè)給定間隔(低和高)之間的所有armstrong數(shù)字。
正整數(shù)稱(chēng)為n階的阿姆斯特朗數(shù),如果
abcd... = an + bn + cn + dn + ...
對(duì)于3位的阿姆斯特朗數(shù)字,每個(gè)數(shù)字的立方數(shù)之和等于數(shù)字本身。例如:
153 = 1*1*1 + 5*5*5 + 3*3*3 // 153是一個(gè)阿姆斯特朗數(shù)。
該程序基于如何檢查整數(shù)是否為Armstrong數(shù)字的概念。
public class Armstrong {
public static void main(String[] args) {
int low = 999, high = 99999;
for(int number = low + 1; number < high; ++number) {
int digits = 0;
int result = 0;
int originalNumber = number;
//位數(shù)計(jì)算
while (originalNumber != 0) {
originalNumber /= 10;
++digits;
}
originalNumber = number;
//結(jié)果包含其數(shù)字的n次冪的和
while (originalNumber != 0) {
int remainder = originalNumber % 10;
result += Math.pow(remainder, digits);
originalNumber /= 10;
}
if (result == number)
System.out.print(number + " ");
}
}
}運(yùn)行該程序時(shí),輸出為:
1634 8208 9474 54748 92727 93084
在上述程序中,檢查了給定間隔高和低之間的每個(gè)數(shù)字。
每次檢查后,digits和result將恢復(fù)為0。