uva 993 Product of digits(分解因子)

               

题目连接:993 - Product of digits


题目大意:给出一个正整数, 要求找到一个自然数,使得该自然数的每一位的数字的乘积等于正整数。并且要求最小,不存在输出-1.


解题思路:将正整数分解因子,注意这里要从9开始, 因为要求值最小,即对应的位数也要最小,所以分解的的因子要尽量最大, 但是不能超过9,10以上是两位数。

1是比较特殊的情况, 因为终止条件是n == 1和i < 2, 所以一开始就要处理掉1的情况,单独考虑, 然后当因子全部分解完之后,n 仍然不等1,说明不能完全分解成2 ~9之间的因子,输出-1.


#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;const int N = 40;int num[N];int main () {    int cas, n, cnt;    scanf("%d", &cas);    while (cas--) { scanf("%d", &n); memset(num, 0, sizeof(num)); cnt = 0if (n != 1) {     for (int i = 9; i > 1; i--) {  while (n % i == 0) {      num[cnt++] = i;      n = n / i;  }  if (n == 1break;     }     sort(num, num + cnt);     if (n != 1)  printf("-1\n");     else {  for (int i = 0; i < cnt; i++)      printf("%d", num[i]);  printf("\n");     } } else      printf("1\n");    }    return 0;}


           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

猜你喜欢

转载自blog.csdn.net/cfhgcvb/article/details/86656164