【Lucas】 HDOJ 5226 Tom and matrix
1917 단어 lucas
#include <iostream>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <climits>
#include <cstdlib>
#include <math.h>
#include <time.h>
#define maxn 100005
#define maxm 80005
#define eps 1e-7
//#define mod 1000000007
#define INF 0x3f3f3f3f
#define PI (acos(-1.0))
#define lowbit(x) (x&(-x))
#define mp make_pair
#define ls o<<1
#define rs o<<1 | 1
#define lson o<<1, L, mid
#define rson o<<1 | 1, mid+1, R
#define pii pair<int, int>
#pragma comment(linker, "/STACK:16777216")
typedef long long LL;
typedef unsigned long long ULL;
//typedef int LL;
using namespace std;
int mod;
//LL qpow(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base;base=base*base;b/=2;}return res;}
LL powmod(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base%mod;base=base*base%mod;b/=2;}return res;}
//head
LL f[maxn];
LL g[maxn];
int x, xx, y, yy;
void init()
{
int mx = max(xx, yy) + 1;
mx = min(mx, mod-1);
f[0] = 1;
for(int i = 1; i <= mx; i++) f[i] = f[i-1] * i % mod;
g[mx] = powmod(f[mx], mod - 2);
for(int i = mx-1; i >= 0; i--) g[i] = g[i+1] * (i + 1) % mod;
}
LL Lucas(int n, int m)
{
if(m > n) return 0;
if(n < mod && m < mod) return f[n] * g[m] % mod * g[n - m] % mod;
return Lucas(n / mod, m / mod) * Lucas(n % mod, m % mod) % mod;
}
void work()
{
LL ans = 0;
for(int i = y; i <= yy; i++) {
ans = (ans + Lucas(xx+1, i+1)) % mod;
ans = (ans - Lucas(x, i+1)) % mod;
}
printf("%lld
", (ans + mod) % mod);
}
int main()
{
while(scanf("%d%d%d%d%d", &x, &y, &xx, &yy, &mod)!=EOF) {
init();
work();
}
return 0;
}