1、
组合数与杨辉三角有对应关系:
#include <iostream>
#include <math.h>
using namespace std;
const int maxn=1e6+20;
const int mod=1e9+7;
typedef long long ll;
ll C[1005][1005];
void getC(int n)
{
for(int i=0;i<=n;i++)
{
for(int j=0;j<=i;j++)
{
if(j==0||j==i)
C[i][j]=1;
else C[i][j]=(C[i-1][j]+C[i][j-1])%mod;
}
}
}
int main(){
int n;
cin>>n;
getC(n);
for(int i=0;i<=n;i++)
{
for(int j=0;j<=i;j++)
{
cout<<C[i][j]<<' ';
}
cout<<endl;
}
return 0;
}
2、
如果 𝑛,𝑚 很小(不超过50),可以用C++的库函数 double tgamma(double x) ,这是一个欧拉积分
在整数点处的取值满足
𝛤(𝑛+1)=𝑛!
因此代码可以这么写
#include <iostream>
#include <math.h>
using namespace std;
const int maxn=1e6+20;
const int mod=1e9+7;
typedef long long ll;
int main(){
ll n,m;
while(cin>>n>>m)
{
ll res=round(tgamma(n+1)/tgamma(m+1)/tgamma(n-m+1));
cout<<res<<endl;
}
return 0;
}
3、
如果 𝑛,𝑚 比较大,可以开 𝑂(𝑛) 的空间
#include <iostream>
#include <math.h>
using namespace std;
const int maxn=1e6+20;
const int mod=1e9+7;
typedef long long ll;
ll gC(ll n,ll m)
{
static ll M=0,inv[maxn],mul[maxn],invMul[maxn];
while(M<=n)
{
if(M)
{
inv[M]=M==1?1:(mod-mod/M)*inv[mod%M]%mod;
mul[M]=mul[M-1]*M%mod;
invMul[M]=invMul[M-1]*inv[M]%mod;
}
else mul[M]=1,invMul[M]=1;
M++;
}
return mul[n]*invMul[m]%mod*invMul[n-m]%mod;
}
int main(){
ll n,m;
while(cin>>n>>m){
ll res=gC(n,m);
cout<<res<<endl;
}
return 0;
}
4、
求素数:
#include <iostream>
#include <math.h>
using namespace std;
const int maxn=1e6+20;
const int mod=1e9+7;
typedef long long ll;
ll C[1005][1005];
bool vis[maxn];
ll prime[maxn];
ll getPrime(ll n){
ll tot=0;
for(ll i=1;i<=n;i++) vis[i]=false;
for(ll i=2;i<=n;i++)
{
if(!vis[i]) prime[tot++]=i;
for(ll j=0;j<tot;j++)
{
if(prime[j]*i>n)
break;
vis[prime[j]*i]=true;
if(i%prime[j]==0)
break;
}
}
return tot;
}
int main()
{
ll n;
cin>>n;
int m=getPrime(n);
for(int i=0;i<m;i++)
cout<<prime[i]<<' ';
cout<<endl;
return 0;
}