NEFU 119 组合素数 (n!素因数p的幂的求法)

组合素数

Problem : 119

Time Limit : 1000ms

Memory Limit : 65536K

description

 
小明的爸爸从外面旅游回来给她带来了一个礼物,小明高兴地跑回自己的房间,拆开一看是一个很大棋盘(非常大),小明有所失望。不过没过几天发现了大棋盘的好玩之处。从起点(0,0)走到终点(n,n)的非降路径数是C(2n,n),现在小明随机取出1个素数p, 他想知道C(2n,n)恰好被p整除多少次?小明想了很长时间都没想出来,现在想请你帮助小明解决这个问题,对于你来说应该不难吧!

input

 
有多组测试数据。
第一行是一个正整数T,表示测试数据的组数。接下来每组2个数分别是n和p的值,这里1<=n,p<=1000000000。

output

 
对于每组测试数据,输出一行,给出C(2n,n)被素数p整除的次数,当整除不了的时候,次数为0。

sample_input

 
2
2 2
2 3

sample_output

 
1
1


 

 

 

 

思路:

C2n,n=( (2n)! ) / (n!*n!)

求上式可以被素数p整除多少次,也就是求上式中素数p的幂

所以统计2n!的幂和(n*n!)的幂,相减就可以了,但要注意统计幂的时候要用long long

定理:n! 的素因子分解中的素数p的指数(幂)为【n/p+n/p^2+n/p^3+.......

代码实现:

#include<cstdio>  
#include<cstring>  
#include<cstdlib>  
#include<cctype>  
#include<cmath>  
#include<iostream>  
#include<sstream>  
#include<iterator>  
#include<algorithm>  
#include<string>  
#include<vector>  
#include<map>  
using namespace std;  
const double eps = 1e-8;  
typedef long long ll;  
typedef unsigned long long ULL;  
const int INF = 0x3f3f3f3f;  
const int INT_M_INF = 0x7f7f7f7f;  
 
const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1};  
const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1};  
const int MOD = 1e9 + 7;  
const double pi = acos(-1.0);  
const int MAXN=5010;  
const int MAXM=100010;
const int M=50010;
ll cal(ll n,ll p)
{
    ll num=0;
	while (n)
	{
		num+=n/p;
		n=n/ p;
	}
    return num;
}
int main()
{
   ll n,p;
   int t;
   cin>>t;
   while(t--)
   {
   	scanf("%lld%lld",&n,&p);
	printf("%lld\n",cal(2*n,p)-2*cal(n,p));
   }
   return 0;
}

猜你喜欢

转载自blog.csdn.net/sdz20172133/article/details/81448442
119