整数因子分解问题

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;
}


  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张之海

若有帮助,客官打赏一分吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值