TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
- C语言趣味程序百例精解之JAVA实现(24)阿姆斯特朗数
- [img]http://img.javaxxz.com/2014/11/16/000927125.jpg[/img]
- 程序
- 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:
- ");
- 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 Test24
- There are following Armstrong number smaller than 1000:
- 153 370 371 407
-
复制代码
源码下载:http://file.javaxxz.com/2014/11/16/000927625.zip |
|