Fzu 2020-Combination (Lucas theorem + inverse solution to solve large combinatorial number modulo)

Source: Internet
Author: User

Title Address: Fzu 2020
Test instructions: The value of C (n,m)%p (1 <= m <= n <= 10^9, M <= 10^4, M < p < 10^9, p is prime).
Ideas:
For and and P is prime, we generally use the Lucas theorem to solve.
1). Lucas theorem is used to find the value of C (n,m) mod p, p is the prime number. It is described as:
If

So get

That
Lucas (N,M,P) =c (n%p,m%p) * Lucas (N/P,M/P,P)
Lucas (n,0,p) = 1;
2). For the large combined number of modulo C (n,m)%p=n! /(m! * (n-m)!)% MoD
= (n-m+i)! /m!* (I>=1&&I<=M). Then divide the division into multiplication according to the multiplication inverse.

#include <stdio.h>#include <math.h>#include <string.h>#include <stdlib.h>#include <iostream>#include <sstream>#include <algorithm>#include <set>#include <queue>#include <stack>#include <map>#include <bitset>#pragma COMMENT (linker, "/stack:102400000,102400000")using namespace STD;typedef__int64 LL;Const intinf=0x3f3f3f3f;Const DoublePi=ACOs(-1.0);Const Doubleesp=1e-6;using namespace STD; LL N,m,mod; ll Modxp (ll A,ll b) {ll res=1; while(b>0) {if(b&1) Res=res*a%mod; B=b>>1;    A=a*a%mod; }returnRes;} ll C (ll N, ll m) {if(m>n)return 0; LL ans=1; for(intI=1; i<=m;        i++) {LL a= (n+i-m)%mod;        LL B=i%mod; Ans=ans* (A*MODXP (b, mod-2)%mod)%mod; }returnAns;} ll Lucas (ll n,ll m) {if(m==0)return 1;returnC (N%mod,m%mod) *lucas (N/mod,m/mod)%mod;}intMain () {intTscanf("%d", &t); while(t--) {scanf("%lld%lld%lld", &n,&m,&mod);printf("%lld\n", Lucas (n,m)); }return 0;}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Fzu 2020-Combination (Lucas theorem + inverse solution to solve large combinatorial number modulo)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.