1. 程式人生 > >Sum of Factorials【貪心+遞迴】

Sum of Factorials【貪心+遞迴】

Given an integer n, you have to find whether it can be expressed as summation of factorials. For given n, you have to report a solution such that

n = x1! + x2! + ... + xn! (xi < xj for all i < j)

Input

Input starts with an integer T (≤ 10000), denoting the number of test cases.

Each case starts with a line containing an integer n (1 ≤ n ≤ 1018

).

Output

For each case, print the case number and the solution in summation of factorial form. If there is no solution then print'impossible'. There can be multiple solutions, any valid one will do. See the samples for exact formatting.

Sample Input

Output for Sample Input

4

7

7

9

11

Case 1: 1!+3!

Case 2: 0!+3!

Case 3: 1!+2!+3!

Case 4: impossible

Note

Be careful about the output format; you may get wrong answer for wrong output format.

題意:N如果可以表示成某幾個數的階乘則找出這幾個數,不能的話輸出impossible,不能有x相同的的數;

思路:N達到lld的限度o(N)的複雜度都不行,不能打表所有數,但是可以打出階乘的表因為20!>2*10^18,就19項就行了,那所有數的組合就是2^19,6位數打表能打,但是所有數之和加起來lld都存不了dp就pass了,只有一個一個判斷嘍, 了N要麼直接就等於一個數的階乘要麼大於一個數的階乘,等於的話直接記錄這個數就行,如果大於的話,要組成階乘的形式,必須要選這個數,如果不選,那麼比這個數小的所有數的階乘之和都不能取代這個數,這就是貪心選擇了,每次找到一個<=N的最大的階乘,然後用N減去這個階乘形成了有一個N,遞迴判斷就行;