UVa 993: Product of digits
这道题很简单。先将N用2,3,5,7(即10以内的素数)分解因数(需要先特殊判断N不为1),然后将可以合并的因数合并(如2*2合并成4,)这样求得的结果位数会减少,大小肯定会小一些。具体实现见代码。
我的解题代码如下:
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <string> #include <algorithm> using namespace std; int c[12]; int T; int N; int main() { cin >> T; while(T--) { cin >> N; if(N==1) { cout << 1 << endl; continue; } memset(c,0,sizeof(c)); while(N!=1) //分解N { if(N%2==0) { c[2]++; N/=2; } else if(N%3==0) { c[3]++; N/=3; } else if(N%5==0) { c[5]++; N/=5; } else if(N%7==0) { c[7]++; N/=7; } else break; } if(N!=1) { cout << -1 << endl; continue; } while(1) //合并N的因子 { if(c[2]>=3) { c[2]-=3; c[8]++; } //因子有三个2,合并为8 else if(c[2]>=2) { c[2]-=2; c[4]++; } //有两个2,合并为4 else if(c[3]>=2) { c[3]-=2; c[9]++; } //有两个3,合并为9 else if(c[2]>=1 && c[3]>=1) { c[2]--; c[3]--; c[6]++; } //有一个2和一个3,合并为6 else break; } for(int i=2; i<=9; i++) {//输出结果 while(c[i]) { cout << i; c[i]--; } } cout << endl; } return 0; }
附上题目如下:
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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)