Pome资料库
Pome 切换暗/亮/自动模式 切换暗/亮/自动模式 切换暗/亮/自动模式 返回首页

阿姆斯壮数

说明

在三位的整数中,例如153可以满足 \(1^3 + 5^3 + 3^3 = 153\),这样的数称之为Armstrong数,试写出一程式找出所有的三位数Armstrong数。

解法

Armstrong数的寻找,其实就是在问如何将一个数字分解为个位数、十位数、百位数……,这只要使用除法与馀数运算就可以了,例如输入 input为abc,则:

a = input / 100

b = (input%100) / 10

c = input % 10

参考代码

C

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h> 
#include <time.h> 
#include <math.h> 

int main(void) { 
    int a, b, c; 
    int input; 

    printf("寻找Armstrong数:\n"); 

    for(input = 100; input <= 999; input++) { 
        a = input / 100; 
        b = (input % 100) / 10; 
        c = input % 10; 
        if(a*a*a + b*b*b + c*c*c == input) 
            printf("%d ", input); 
    } 

    printf("\n"); 

    return 0; 
}

Java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
public class Armstrong {
    public static void main(String[] args) {
        System.out.println("寻找Armstrong数:"); 

        for(int i = 100; i <= 999; i++) { 
                int a = i / 100; 
                int b   = (i % 100) / 10; 
                int c = i % 10; 
                if(a*a*a + b*b*b + c*c*c == i) 
                        System.out.print(i + " "); 
        } 

        System.out.println();
    }
}