|
C语言趣味程序百例精解之java实现(24)阿姆斯特朗数程序
public class Test24{
public static void main(String args[]){
new Test24().AMSTL();
}
/**
* 24.阿姆斯特朗数
*/
public void AMSTL(){
int a[]=new int[3];
System.out.printf("There are following Armstrong number smaller than 1000:\n");
for(int i=2;i<1000;i++){
for(int t=0,k=1000;k>=10;t++){
a[t]=(i%k)/(k/10);
k/=10;
}
if(a[0]*a[0]*a[0]+a[1]*a[1]*a[1]+a[2]*a[2]*a[2]==i)
System.out.printf("%d ",i);
}
}
public void AMSTL24() {
for (int i = 1; i < 9999; i++) {
int s = 0;
for (int j = 1; j < getBitCount(i) + 1; j++) {
s += (getThe(i, j) * getThe(i, j) * getThe(i, j));
}
if (s == i)
System.out.println("I got one :" + i);
}
}
/**
* 获取一个数的位数
*/
public int getBitCount(int n) {
int i = 1;
while (n / 10 > 0) {
i++;
n /= 10;
}
return i;
}
/**
* 获取N位数第i位
*/
public int getThe(int num, int i) {
if (i > getBitCount(num) || i < 1)
return -1;
return (num % ((int) Math.pow(10, i))) / (int) Math.pow(10, i - 1);
}
}
运行:
C:\java>java Test24There are following Armstrong number smaller than 1000:153 370 371 407 |
|