简体   繁体   中英

How to calculate number of partitions of n?

How can I calculate number of partitions of n mod 1e9+7 , where n<=50000 .

See http://oeis.org/A000041 .

Here is the source problem http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1259 (In Chinese)

Simply applying the formula: a(n) = (1/n) * Sum_{k=0..n-1} d(nk)*a(k) gave me an O(n^2) solution.

typedef long long ll;
ll MOD=1e9+7;
ll qp(ll a,ll b)
{
    ll ans=1;
    while(b)
    {
        if(b&1) ans=ans*a%MOD;
        a=a*a%MOD;
        b>>=1;
    }
    return ans;
}
ll a[50003],d[50003];
#define S 1000
int main()
{
    for(int i=1; i<=S; i++)
    {
        for(int j=1; j<=S; j++)
        {
            if(i%j==0) d[i]+=j;
        }
        d[i]%=MOD;
    }
    a[0]=1;
    for(int i=1; i<=S; i++)
    {
        ll qwq=0;
        for(int j=0; j<i; j++) qwq=qwq+d[i-j]*a[j]%MOD;
        qwq%=MOD;
        a[i]=qwq*qp(i,MOD-2)%MOD;
    }
    int n;
    cin>>n;
    cout<<a[n]<<"\n";
}

I would solve it with a different approach.

Dynamic Programming:

DP[N,K] = number of partitions of N using only numbers 1..K
DP[0,k] = 1
DP[n,0] = 0
DP[n,k] when n<0 = 0
DP[n,k] when n>0 = DP[n-k,k] + DP[n,k-1]

Recursive implementation using memoization:

ll partition(ll n, ll max){
    if (max == 0)
        return 0;
    if (n == 0)
        return 1;
    if (n < 0)
        return 0;

    if (memo[n][max] != 0)
        return memo[n][max];
    else
        return (memo[n][max] = (partition(n, max-1) + partition(n-max,max)));
}

Live-Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM