UVa 993 Product of digits(简单数论)

来源:互联网 发布:淘宝页面怎么做 编辑:程序博客网 时间:2024/05/17 03:43

993 - Product of digits

Time limit: 3.000 seconds

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=113&page=show_problem&problem=934

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 (0$ \le$N$ \le$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,是否存在这样的数Q,Q的所有位上的数之积等于N?

思路:

将N素因数分解,再合并整理即可。

复杂度:O(log N)

完整代码:

/*0.012s*/#include <cstdio>#include <cstring>int main(){int t, index[8];scanf("%d", &t);flag:while (t--){memset(index, 0, sizeof(index));int n;scanf("%d", &n);if (n <= 1){printf("%d\n", n);continue;}//分解Nwhile (n != 1){int count = 0;if (!(n & 1)) index[0]++, n >>= 1;else count++;if (!(n % 3)) index[1]++, n /= 3;else count++;if (!(n % 5)) index[3]++, n /= 5;else count++;if (!(n % 7)) index[5]++, n /= 7;else count++;if (count == 4){puts("-1");goto flag;}}//2^3=8index[6] += index[0] / 3, index[0] %= 3;//2^2=4if (index[0] == 2) index[2] = 1, index[0] = 0;//3^2=9index[7] += index[1] >> 1, index[1] &= 1;//2*3=6if (index[0] & index[1]) index[4] = 1, index[1] = index[0] = 0;for (int i = 0; i < 8; ++i)while (index[i]--) putchar(i + 50);putchar(10);}return 0;}

原创粉丝点击