Product of Digits
題意: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 .
輸入一個正整數N,決定有幾個case,再輸入N個數字,找出一個所有digit相乘會等於輸入數的數字(由小到大),若找不到,則印出-1。
輸入範例:3
1
10
123456789
輸出範例:1
25
-1
解法:
設定一個方法,裡面有一個大小為1000儲存答案的陣列,先檢查是否為1,的話直接印出一;不是的話再做下列步驟,用for迴圈將這個數字從9檢查到2,看共有幾個2到9的因數,在while裡檢查的則是是否有重複數字的因數,(如81為9*9),有的話就存入陣列。在for迴圈執行結束後,判斷原先輸入的數字是否被除成1,是的話代表有答案,將儲存答案的陣列由後往前全部印出來,若不是1則代表沒有答案,印出-1。
程式:#include <iostream>
using namespace std;
int main(){
int num;
int does;
void seq_dig(int);
cin >> does ;
for(int i=0;i<does;i++){
cin >> num;
seq_dig(num);
}
return 0;
}
void seq_dig(int num){
int ans[1000];
int store=0;
if(num!=1){
for(int tst_dig=9;tst_dig>1;tst_dig--){
while(num!=1){
if(num%tst_dig){
break; //the tst_dig is not divisor of num
}
else{
num/=tst_dig;
ans[store]=tst_dig;
store++;
}
}
}
if(num==1){
for(int i=store-1;i>=0;i--)
cout <<ans[i] ;
cout <<endl;
}
else{
}
}
else{
cout << "1"<<endl;
}
}
cout << "-1" <<endl;