hdu 5407【LCM性质】+【逆元】(结论题)

本文探讨了如何求解组合数的最小公倍数(LCM)问题,给出了一种高效算法,即通过质因数分解法求解1到n的LCM,并利用逆元知识处理大数问题。

<题目链接>

<转载于 >>> >    

Problem Description
CRB has  N different candies. He is going to eat K candies.
He wonders how many combinations he can select.
Can you answer his question for all K(0 ≤ K ≤ N)?
CRB is too hungry to check all of your answers one by one, so he only asks least common multiple(LCM) of all answers.
 
Input
There are multiple test cases. The first line of input contains an integer  T, indicating the number of test cases. For each test case there is one line containing a single integer N.
1 ≤ T ≤ 300
1 ≤ N ≤ 106
 
Output
For each test case, output a single integer – LCM modulo 1000000007( 109+7).
 
Sample Input
5
1
2
3
4
5
 
Sample Output
1
2
3
12
10
 

题目大意:

题目大意就是求 :    lcm(C(n,0),C(n,1),C(n,2),,,,C(n,n))

 

解题分析:

有一个对应的结论: lcm(C(n,0),C(n,1),C(n,2),,,,C(n,n))  =   lcm(1,2,,,,n,n+1)/(n+1)。

于是这道题就变成了求(1~n)的lcm,当然,直接暴力求解会超时,还有求LCM的更加高效的解法,叫做分解质因数法。并且,由于(n+1)可能很大,所以还要用到逆元的知识。

辅助理解的博客 >>> 

 

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
using namespace std;
typedef long long LL;
const int N = 1000005;
const LL mod = 1000000007;
LL f[N];
LL gcd(LL a,LL b){
    return b==0?a:gcd(b,a%b);
}

LL extend_gcd(LL a,LL b,LL &x,LL &y){
    if(!b){
        x=1,y = 0;
        return a;
    }else{
        LL x1,y1;
        LL d = extend_gcd(b,a%b,x1,y1);
        x = y1;
        y = x1 - a/b*y1;
        return d;
    }
}
LL mod_reverse(LL a,LL n)
{
    LL x,y;
    LL d=extend_gcd(a,n,x,y);
    if(d==1) return (x%n+n)%n;
    else return -1;
}
int prime[N];
LL F[N];
bool only_divide(int n){
    int t = prime[n];
    while(n%t==0){
        n/=t;
    }
    if(n==1) return true;
    return false;
}
void init(){
    for(int i=1;i<N;i++){
        prime[i] = i;
    }
    for(int i=2;i<N;i++){  ///十分巧妙的一步,判断某个数是否只有唯一的质因子,只需要把每个数的倍数存下来
        if(prime[i]==i){
            for(int j=i+i;j<N;j+=i){
                prime[j] = i;
            }
        }
    }
    F[1] = 1;
    for(int i=2;i<N;i++){
        if(only_divide(i)){
            F[i] = F[i-1]*prime[i]%mod;
        }else F[i] = F[i-1];
    }
}
int main()
{
    init();
    int tcase;
    scanf("%d",&tcase);
    while(tcase--)
    {
        int n;
        scanf("%d",&n);
        LL inv = mod_reverse((n+1),mod);
        printf("%lld\n",F[n+1]*inv%mod);
    }
    return 0;
}

 

 

2018-07-30

转载于:https://www.cnblogs.com/00isok/p/9393223.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值