整数因子分解问题
2015-10-18 11:28
435 查看
Problem Description
大于1 的正整数n可以分解为:n=x1*x2*…*xm。 例如,当n=12 时,共有8 种不同的分式: 12=12; 12=6*2; 12=4*3; 12=3*4; 12=3*2*2; 12=2*6; 12=2*3*2; 12=2*2*3。 编程任务:
对于给定的正整数n,编程计算n共有多少种不同的分解式。
Input
1个正整数n (1≤n≤2000000000)。
Output
1个正整数,即计算出的不同的分解式数
Sample Input
12
Sample Output
8
===================================================================================
法(1):简单递归方式求解
法(2):dp方式求解
大于1 的正整数n可以分解为:n=x1*x2*…*xm。 例如,当n=12 时,共有8 种不同的分式: 12=12; 12=6*2; 12=4*3; 12=3*4; 12=3*2*2; 12=2*6; 12=2*3*2; 12=2*2*3。 编程任务:
对于给定的正整数n,编程计算n共有多少种不同的分解式。
Input
1个正整数n (1≤n≤2000000000)。
Output
1个正整数,即计算出的不同的分解式数
Sample Input
12
Sample Output
8
===================================================================================
法(1):简单递归方式求解
<span style="font-size:18px;">#include <cstdio> #include <iostream> using namespace std; int count; void solve(int n){ if(n == 1){ //叶子结点 count ++; }else{ for(int i=2;i<=n;i++){//某一个非叶子结点下的下一层所有子结点 if(n%i == 0) solve(n/i); } } } int main(){ int n; while(cin >> n){ count = 0; solve(n); cout<<"The number of solution is "<<count<<endl; } }</span>
法(2):dp方式求解
#include <iostream> #include <algorithm> #include <cstdio> #define maxn 100 using namespace std; int yueShu[maxn],length=0; int dp[maxn]; //dp[i]中保存的是i的解决方案数 void approximateNumber(int n) { int i; for(i=1;i*i<n;i++) // if(n%i==0) { yueShu[length ++] = i; yueShu[length ++] = n/i; } if(i*i==n) yueShu[length++]=i; sort(yueShu,yueShu+length); } void dpSolve(int n) { int i; dp[0]=1;//yueShu[0]=1,值最小,就只有一个约数。 -| // | ->遍历yueShu[maxn] for(i=1;i<length;i++)// -| { dp[i]=0; for(int j=0;j<i;j++) if(yueShu[i]%yueShu[j]==0) dp[i]+=dp[j]; } } /*! eg: 约数 : 1 2 3 4 6 12 解决方案数: 1 1 1 2 3 8 8= 1 + 1 + 1 + 2 + 3; 12 = 1*12 = 2*6 = 3*4 = [4*3] = (1*4)*3 = (2*2)*3 = [6*2] = (1*6)*2 = (2*3)*2 = (3*2)*2 12 = 4*3; 而4=(1*4); 4=(2*2); 故 12 = (1*4)*3; = (2*2)*3 所以会加上dp[4]=2 */ int main() { int n; while(cin>>n){ approximateNumber(n);//求n的约数 dpSolve(n); cout<<dp[length-1]<<endl; } return 0; }
相关文章推荐
- 给应用程序传递参数
- 病毒的认识
- 功能自动化测试工具列表大全
- LInux 删除驱动
- inet_pton, inet_ntop
- [C++基金会]位计算 游戏开发中的应用
- LeetCode OJ:Combinations (排列组合)
- 网页里面嵌入视频代码
- GitHub 优秀的 Android 开源项目
- 基于Theano的深度学习(Deep Learning)框架Keras学习随笔-07-初始化权值
- BZOJ1066[SCOI2007]蜥蜴
- linux读书笔记5
- matlab初学笔记(二)
- win10 预览版10568怎么样 Win10 Build 10568更新了什么
- 孩子分糖问题----
- 剑指offer第十九题【顺时针打印矩阵】c++实现
- 服务启动错误1053解决方案之一
- setprecision、fixed、showpoint的用法总结
- 关于差分约束系统的再理解
- ASP.NET比较常用的26个性能优化技巧