一個N位的十進制正整數,若是它的每一個位上的數字的N次方的和等於這個數自己,則稱其爲花朵數。
例如:
當N=3時,153就知足條件,由於 1^3 + 5^3 + 3^3 = 153,這樣的數字也被稱爲水仙花數(其中,「^」表示乘方,5^3表示5的3次方,也就是立方)。
當N=4時,1634知足條件,由於 1^4 + 6^4 + 3^4 + 4^4 = 1634。
當N=5時,92727知足條件。
實際上,對N的每一個取值,可能有多個數字知足條件。
程序的任務是:求N=21時,全部知足條件的花朵數。注意:這個整數有21位,它的各個位數字的21次方之和正好等於這個數自己。
若是知足條件的數字不僅有一個,請從小到大輸出全部符合條件的數字,每一個數字佔一行。由於這個數字很大,請注意解法時間上的可行性。
java
import java.math.BigInteger; import java.util.HashMap; public class PTest2 { /** * @param args */ private static HashMap<String,BigInteger> h = new HashMap<String,BigInteger>(); private static HashMap<String,BigInteger> n = new HashMap<String,BigInteger>(); static{ for(int i=0;i<10;i++){ h.put("h"+i,new BigInteger(String.valueOf(i)).pow(21)); } for(int j=0;j<=21;j++){ n.put("n"+j, new BigInteger(String.valueOf(j))); } } public static void isequal(int[] nums){ BigInteger sum = BigInteger.ZERO; boolean b = true; int[] num = new int[10]; String str = null; for(int i=0;i<10;i++){ if(nums[i]>0)sum = sum.add(h.get("h"+i).multiply(n.get("n"+nums[i]))); } if(!sum.equals(BigInteger.ZERO)){ str = sum.toString(); //System.out.println(str); if(str.length()==21){ for(int j=0;j<str.length();j++){ //System.out.println(str.charAt(j)+" "); num[str.charAt(j)-'0']++; } for(int k=0;k<10;k++){ if(num[k]!=nums[k]){ b = false; break; } } if(b) System.out.println(str); } } } public static void test(int a){ int[] nums = new int[10]; nums[9]=a; for(int b = 0;b<=21-a;b++){ nums[8]=b; for(int c = 0;c<=21-a-b;c++){ nums[7]=c; for(int d = 0;d<=21-a-b-c;d++){ nums[6]=d; for(int e = 0;e<=21-a-b-c-d;e++){ nums[5]=e; for(int f = 0;f<=21-a-b-c-d-e;f++){ nums[4]=f; for(int g = 0;g<=21-a-b-c-d-e-f;g++){ nums[3]=g; for(int h = 0;h<=21-a-b-c-d-e-f-g;h++){ nums[2]=h; for(int i = 0;i<=21-a-b-c-d-e-f-g-h;i++){ nums[1]=i; nums[0]=21-a-b-c-d-e-f-g-h-i; PTest2.isequal(nums); } } } } } } } } } public static void main(String[] args) { // TODO Auto-generated method stub Task t = null; for(int a=0;a<10;a++){ t=new Task(); t.setA(a); new Thread(t).start(); } } } class Task implements Runnable{ private int a=0; @Override public void run() { // TODO Auto-generated method stub PTest2.test(a); } public void setA(int a1){ this.a=a1; } }