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 (0N
109) .
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
方法 :
如果 n < 10,直接返回n
否则 从9到2计算n中的最大次幂数,n = 9^x8^y...2^z
然后计算n按因子升序将每个因子幂的个数展开的值,即为所求。
代码:
#include int min_num(int n) { int i, t, digit[10]; for(i = 0; i < 10; i++) digit[i] = 0; if(n < 10) return n; for(i = 9; i > 1; i--){ while(n > 1 && (n % i) == 0){ digit[i]++; n /= i; } } if(n > 9) return -1; t = 0; for(i = 2; i < 10; i++){ while(digit[i]){ t = t * 10 + i; digit[i]--; } } return t; } int main() { int t, n; scanf("%d", &t); while(t-- > 0){ scanf("%d", &n); printf("%d\n", min_num(n)); } return 0; }