Your task in this problem is to determine the number of divisors of Cnk. Just for fun -- or do you need any special reason for such a useful computation?
Input
The input consists of several instances. Each instance consists of a single line containing two integers n and k (0 ≤ k ≤ n ≤ 431), separated by a single space.
Output
For each instance, output a line containing exactly one integer -- the number of distinct divisors of Cnk. For the input instances, this number does not exceed 2 63 - 1.
Sample Input
5 1
6 3
10 4
Sample Output
2
6
16
思路:
一开始暴力,结果T了,后来预处理打表,不过这个表打的比较暴力。看到别人分解n!的因子时好像有技巧。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<string>
#include<vector>
#include<complex>
using namespace std;
typedef long long ll;
int prime[100000],vis[100000];
ll yz[600][600],ans[600][600];
void init()
{
for(int i=2;i<=435;i++)
{
if(vis[i]) continue;
prime[++prime[0]]=i;//prime[0]记录的是元素个数
for(int j=2;j*i<=435;j++)
vis[i*j]=1;
}
}
void solve()
{
for(int i=1;i<=440;i++)
{
int x=i;
for(int j=1;j<=prime[0];j++)//从1开始
while(x%prime[j]==0){
yz[i][j]++;
x/=prime[j];
}
for(int j=0;j<=prime[0];j++)
yz[i][j]+=yz[i-1][j];
}
for(int i=1;i<=440;i++){
for(int j=0;j<=i;j++){
ans[i][j]=1;
for(int k=1;k<=prime[0];k++){
ll all=yz[i][k]-yz[j][k]-yz[i-j][k];
ans[i][j]*=(all+1);
}
}
}
}
int main()
{
init();
solve();
int n,k;
ans[0][0]=1;//一开始没算上0 0
while(~scanf("%d%d",&n,&k))
{
printf("%lld\n",ans[n][k]);
}
return 0;
}
另一种分解因子的方式:(主要区别在solve函数中)
下面一段话转自:该博客
在说方法前,先说一个n!的性质:
n!的素因子分解中的素数p的个数为
n/p+n/(p^2)+...+n/(p^k)+...
《ACM-ICPC程序设计系列 数论及应用》上的方法,200+ms:
首先先求解435以内的素因子。
然后预处理出j!中每个素因子的个数,公式如下:
num[j][i]=j/prime[i]+num[j/prime[i]][i];
设n!中素因子p的个数为:a=n/p+n/(p^2)+...+n/(p^k)+...
那么(n/p)!中素因子p的个数为:b=n/(p^2)+...+n/(p^k)+...
很显然a=b+n/p,因此可以利用上述递推公式预处理出所有的j!中每个素因子的个数。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<string>
#include<vector>
#include<complex>
using namespace std;
typedef long long ll;
int prime[100000],vis[100000];
ll yz[600][600],ans[600][600];
void init()
{
for(int i=2;i<=435;i++)
{
if(vis[i]) continue;
prime[++prime[0]]=i;
for(int j=2;j*i<=435;j++)
vis[i*j]=1;
}
}
void solve()
{
for (int i = 1; i <= prime[0]; i++)
for (int j = 1; j < 435; j++) //yz[i][j]表示i!中素因子prime[j]的个数。
yz[j][i] = j/prime[i] + yz[j/prime[i]][i];
for (int i = 1; i < 450; i++)
for (int j = 1; j < i; j++){
ans[i][j] = 1;
for (int k = 1; k <= prime[0]; k++){
int d = yz[i][k] -yz[i-j][k] - yz[j][k];
ans[i][j] *= (d+1); //C[i][j](0<=j<=i)表示组合ans(i,j)的因子个数。
}
}
}
int main()
{
init();
solve();
int n,k;
while(~scanf("%d%d",&n,&k))
{
if (n == k || k == 0) printf("1\n"); else
printf("%lld\n",ans[n][k]);
}
return 0;
}