求21位數的水仙花數

  1. /* 
  2.  * 求21位數的水仙花數 
  3.  */  
  4. import java.math.BigInteger;  
  5.   
  6. public class Demo01_BigInteger {  
  7.     // 求 每個 i 的 21 次方  
  8.     public static BigInteger p(int i){  
  9.         BigInteger base = BigInteger.valueOf(i);  
  10.         return base.pow(21);  
  11.     }  
  12.     public static void ji_suan(BigInteger[] pw,int[] nn){  
  13.         BigInteger sum = BigInteger.ZERO;  
  14.         for(int i=0;i<10;i++){  
  15.             sum = sum.add(  
  16.                     pw[i].multiply(BigInteger.valueOf(nn[i])));  
  17.         }  
  18.         String s = "" + sum;  
  19.         if(s.length()!=21return;  
  20.         // 確定各數字出現的多少次  
  21.         int[] nn2 = new int[10];  
  22.         for(int i=0;i<21;i++){  
  23.             nn2[s.charAt(i)-'0']++;  
  24.         }  
  25.         for(int i=0;i<10;i++){  
  26.             if(nn[i]!=nn2[i]) return;  
  27.         }  
  28.         System.out.println(s);  
  29.     }  
  30.     public static void f(BigInteger[] pw, int[] nn, int cur, int use){  
  31.         if(cur==9){  
  32.             nn[9] = 21 - use;  
  33.             ji_suan(pw,nn);  
  34.             return;  
  35.         }  
  36.         // 對當前位置所有可能進行枚舉  
  37.         for(int i=0;i<21-use;i++){  
  38.             nn[cur] = i;  
  39.             f(pw,nn,cur+1,use+i);  
  40.         }  
  41.     }  
  42.     public static void main(String[] args){  
  43.         long startTime = System.currentTimeMillis();    // 程序開始時間  
  44.         BigInteger pw[] = new BigInteger[10];  
  45.         for(int i=0;i<pw.length;i++){  
  46.             pw[i] = p(i);  
  47.         }  
  48.         int nn[] = new int[10];  
  49.         f(pw,nn,0,0);  
  50.         System.out.println("OK");  
  51.         long endTime = System.currentTimeMillis();  // 程序結束時間  
  52.         System.out.println((endTime-startTime)/1000f+"秒");  // 運行總時間  
  53.     }  
  54. }  
運行結果:
[plain] view plaincopy
  1. 128468643043731391252  
  2. 449177399146038697307  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章