Product of digits
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 .
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
大致题意:
求最小的整数Q,使Q的每位乘起来恰好等于N;
思路:
先求N的因数,如果N的因数有大于10的质数,一定不可能啦!
先求Q除以2,3,5,7,如果最后不是等于1,那就是不可能的。
如果等于1,然后比如:有三个2,可以乘起来得8,位数越少,数一定越小。
#include <iostream>
#include <cstring>
#include <cstdio>
#include<cmath>
#include <algorithm>
using namespace std;
int a[11];
int main()
{
int N,Q,i;
scanf("%d",&N);
while(N--)
{
scanf("%d",&Q);
if(Q==1)
{
printf("1\n");
continue;
}
memset(a,0,sizeof(a));
while(Q!=1)
{
if(Q%2==0) {Q/=2;a[2]++;}
else
if(Q%3==0) {Q/=3;a[3]++;}
else
if(Q%5==0) {Q/=5;a[5]++;}
else
if(Q%7==0) {Q/=7;a[7]++;}
else
break;
}
if(Q!=1)
{
printf("-1\n");
continue;
}
while(a[2]>=3){ a[2]-=3; a[8]++; }
while(a[2]>=2){ a[2]-=2; a[4]++; }
while(a[3]>=2){ a[3]-=2; a[9]++; }
while(a[2]>=1&&a[3]>=1) {a[2]--;a[3]--;a[6]++;}
for(i=2;i<=9;i++)
while(a[i]!=0)
{
cout<<i;
a[i]--;
}
printf("\n");
}
return 0;
}