1. 程式人生 > 其它 >列舉演算法(Enumeration algorithm)例項一

列舉演算法(Enumeration algorithm)例項一

(建議電腦看原文連結,平臺的排版不太好,太累了。)描述:在n位的整數中,例如153可以滿足1^3 + 5^3 + 3^3 = 153,這樣的數稱之為Armstrong數。

將所有的Armstrong數按小到大排序,試寫出一程式找出n位數以下的所有Armstrong數,網上大多數是已知位數求確定位數下的Armstrong數,本題在此基礎上提高了一定的難度。

手機瀏覽圖片,電腦使用者瀏覽下面的程式碼

/**
 * @Author: zhaoyaojing
 * @Email: null
 * @Date: 02/02/2018
 * @Time: 8:53 PM
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ArmstrongNum {
    public ArmstrongNum(){
    }

    /**
     * 列舉法
     * 求n位數以下的所有Armstrong數,也就是10的(n+1)次冪以下的數
     */
    public void getAllArmstrongNum1(int n){

        //從1開始到10的n次冪
        for(int i = 1; i < (int) Math.pow(10, n); i++){

            //sum表示一個i位數等於其個位數的i次方之和,i小於等於n。
            int sum = 0;

            //把每個數查分成i個個位數,放在數組裡
            int[] mun = new int[n];

            //獲得當下查詢值
            int thisNum = i;

            //j為當下查詢值的位數
            int j = 0;

            //得到一個存放當下數每位上的數的陣列mun
            while (thisNum > 0){
                mun[j] = thisNum % 10;
                thisNum = thisNum / 10;
                ++j;
            }

            //求得sum
            for(int k = 0; k < n; k++){
                sum = sum + (int)Math.pow(mun[k], j);
            }

            //如果i屬於Armstrong數,則輸出,以一個空格為間隙。
            if(i == sum){
                System.out.print(i + " ");
            }
        }
    }

    public static void main(String[] args) throws Exception, IOException {
        // TODO Auto-generated method stub
        ArmstrongNum armstrongNum = new ArmstrongNum();
        System.out.print("求n位數以下的Armstrong數,請先輸入n的值:n");

        //輸入n
        int n = Integer.parseInt(new BufferedReader
                (new InputStreamReader(System.in)).readLine());

        //得到n位數以下的所有Armstrong數
        armstrongNum.getAllArmstrongNum1(n);
    }
}
求n位數以下的Armstrong數,請先輸入n的值:
5
1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474 54748 92727 93084