关闭

TOJ 4111 Binomial efficient calculate C(n,k)

标签: TOJacmCombination number
341人阅读 评论(0) 收藏 举报

For Mod 2^n,you can also use &(2^n-1),it will more faster.

M % (2^n) = M & (2^n-1);

It's use a way to get all quality factors of N!.

The portal:http://acm.tju.edu.cn/toj/showp4111.html

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>

const long long  N = 1000000;
long long tag[1000006],p[1000006],numtot;
long long Mod;

long long a1[1000006];

long long Fast_Power(long long n,long long k){
    long long ans = 1;
    while(k){
        if(k & 1) ans = ( ans * n ) % Mod;
        k /= 2;
        n = ( n * n ) % Mod;
    }
    return ans;
}

void Get_prime()
{
    long long  cnt = 0;
    memset(tag,0,sizeof(tag));
    for (long long  i = 2; i <= N; i++)
    {
        if (!tag[i])    p[cnt++] = i;
        for (long long  j = 0; j < cnt && p[j] * i <= N; j++)
        {
            tag[i*p[j]] = 1;
            if (i % p[j] == 0)
                break;
        }
    }
    numtot = cnt;
}

void Deal_with(){
    long long  T,n,k;
    scanf("%lld",&T);
    while(T--){
        scanf("%lld %lld",&n,&k);
        //memset(a1,0,sizeof(a1)); Can't use memset,It's TLE.
        int tempi;
        for(long long  i=0;i<numtot;i++){
            if(p[i] > n)break;
            a1[p[i]] = 0;
            for(long long  j=p[i];j<=n;j *= p[i])a1[p[i]] += n / j;
            for(long long  j=p[i];j<=k;j *= p[i])a1[p[i]] -= k / j;
            for(long long  j=p[i];j<=n-k;j *= p[i])a1[p[i]] -= (n-k) / j;
            tempi = i;
        }
        Mod = 1;
        for(long long  i=1;i<=32;i++){
            Mod *= 2;
        }
        long long ans = 1;
        for(long long  i=0;i<=tempi;i++){//It should use tempi,Because if i > tempi,it's no initialization.
            ans = ( ans * Fast_Power(p[i],a1[p[i]]) ) % Mod;
        }
        printf("%lld\n",ans);
    }
}

int main(void){
    Get_prime();
    Deal_with();
    return 0;
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:69085次
    • 积分:3697
    • 等级:
    • 排名:第9337名
    • 原创:315篇
    • 转载:3篇
    • 译文:0篇
    • 评论:4条
    文章分类
    最新评论