這道題很簡單。先將N用2,3,5,7(即10以內的素數)分解因數(需要先特殊判斷N不爲1),然後將可以合併的因數合併(如2*2合併成4,)這樣求得的結果位數會減少,大小肯定會小一些。具體實現見代碼。
我的解題代碼如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <string>
#include <algorithm>
using namespace std;
int c[12];
int T;
int N;
int main()
{
cin >> T;
while(T--)
{
cin >> N;
if(N==1) { cout << 1 << endl; continue; }
memset(c,0,sizeof(c));
while(N!=1) //分解N
{
if(N%2==0) { c[2]++; N/=2; }
else if(N%3==0) { c[3]++; N/=3; }
else if(N%5==0) { c[5]++; N/=5; }
else if(N%7==0) { c[7]++; N/=7; }
else break;
}
if(N!=1) { cout << -1 << endl; continue; }
while(1) //合併N的因子
{
if(c[2]>=3) { c[2]-=3; c[8]++; } //因子有三個2,合併爲8
else if(c[2]>=2) { c[2]-=2; c[4]++; } //有兩個2,合併爲4
else if(c[3]>=2) { c[3]-=2; c[9]++; } //有兩個3,合併爲9
else if(c[2]>=1 && c[3]>=1) { c[2]--; c[3]--; c[6]++; } //有一個2和一個3,合併爲6
else break;
}
for(int i=2; i<=9; i++)
{//輸出結果
while(c[i])
{
cout << i;
c[i]--;
}
}
cout << endl;
}
return 0;
}
附上題目如下:
For a given non-negative integer number N ,
find the minimal natural Q such that the product of all digits of Q is equal N .
Input
The first line of input contains one positive integer number, which is the number of data sets. Each subsequent line contains one data set which consists of one non-negative integer number N (0N109) .
Output
For each data set, write one line containing the corresponding natural number Q or `-1' if Q does not exist.
Sample Input
3 1 10 123456789
Sample Output
1 25 -1