Topic links
Find the smallest cubic number, and its number of members can be arranged to form five cubic numbers.
Resolve Key points:
These five numbers are made up of the same number.
Can be used Hashmap,key is the number of numbers formed by the Key,value record the number of cubic meters made up of these several times
How is key determined?
1. After each digit of this number is sorted, (ascending or descending), the number of re-composition as key
2. According to the number 0-9, the number of occurrences, the composition of the string as a key
Java Program:
Packageproject61;ImportJava.util.HashMap; Public classp62{LongGetKey (int[] digits) {//the mapping here is to change the order of the original number//The number of low-to-high numbers after mapping is getting bigger.//the number in the digits array is the corresponding position of the original number several times.//you can link the numbers in digits directly . LongKey = 0; for(inti=9;i>=0;i--){ while(digits[i]!=0) {Key= key*10+i; Digits[i]--; } } returnkey; } voidrun () {LongA = 0; LongTempa = 0; HashMap<long, integer> HM =NewHashmap<long, integer>(); for(LongI =10000;i>111;i--) {a= i*i*i; Tempa=A; int[] B =New int[10]; LongKey=0; while(a!=0) {b[(int) (A%10)] +=1 ; A=a/10; } Key=GetKey (b); intValue = Hm.get (key) = =NULL? 1: (Integer) Hm.get (key) +1; if(value==5) {System.out.println (Tempa); } hm.put (key, value); }} String GetKey1 (int[] digits) { //It's just a simple link from high to low.String str= ""; for(inti=9;i>=0;i--) Str+=digits[i]+ ""; returnstr; } voidrun1 () {LongA = 0; LongTempa = 0; HashMap<string, integer> HM =NewHashmap<string, integer>(); Longi = 10000; while(i>100) {a= i*i*i; Tempa=A; int[] B =New int[10]; String key; while(a!=0) {b[(int) (A%10)] +=1 ; A=a/10; } Key=GetKey1 (b); intValue = Hm.get (key) = =NULL? 1: (Integer) Hm.get (key) +1; if(value==5) {System.out.println (Tempa); } hm.put (key, value); I= I-1; } } Public Static voidMain (string[] args) {Longbegin=System.currenttimemillis (); NewP62 (). RUN1 ();//127035954683 LongEnd =System.currenttimemillis (); LongTime = end-begin; System.out.println ("Time:" +time/1000+ "S" +time%1000+ "MS"); }}
The above program has a small problem: The value is found in descending order, but the output to two results, the small one is the answer.
Python program:
ImportTime as Timeclock=time.time () P={}c={}i= 1J= 5 whileTrue:c=i*i*I k="'. Join (Sorted (str (c)))ifKinchP:p[k]+=1ifP[k] = =J:PrintC[k] Break Else: P[k]= 1C[k]=c i= i + 1Print('Time :', Time.time ()-Clock,'seconds')
The Python program above is very good, defines two dictionaries, one holds the key, and the number of occurrences of value, one is to hold the first number that appears, key, value is the size of this number.
Euler Project question 62nd: Cubic permutations