您的位置:首页 > 其它

整数因子分解问题

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):简单递归方式求解

<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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: