C语言程序设计:c=m!/(n!*(m-n)!)
C(n,m)=n!/(m!*(n-m)!),C(n,m)=p1a1-b1-c1p2a2-b2-c2…pkak-bk-ck,n<=10,000,000
[cpp]
#include<cstdio>
constintmaxn=1000000;
#include<vector>
usingnamespacestd;
boolarr[maxn+1]={false};
vector<int>produce_prim_number()
{
vector<int>prim;
prim.push_back(2);
inti,j;
for(i=3;i*i<=maxn;i+=2)
{
if(!arr[i])
{
prim.push_back(i);
for(j=i*i;j<=maxn;j+=i)
arr[j]=true;
}
}
while(i<maxn)
{
if(!arr[i])
prim.push_back(i);
i+=2;
}
returnprim;
}
//计算n!中素数因子p的指数
intcal(intx,intp)
{
intans=0;
longlongrec=p;
while(x>=rec)
{
ans+=x/rec;
rec*=p;
}
returnans;
}
//计算n的k次方对m取模,二分法
intpow(longlongn,intk,intM)
{
longlongans=1;
while(k)
{
if(k&1)
{
ans=(ans*n)%M;
}
n=(n*n)%M;
k>旁返>=1;
}
returnans;
}
//计算C(n,m)
intcombination(intn,intm)
{
constintM=10007;
vector<int>prim=produce_prim_number();
longlongans=1;
intnum;
for(inti=0;i<prim.size()&&prim[i]<=n;++i)
{
num=cal(n,prim[i])-cal(m,prim[i])-cal(n-m,prim[i]);
ans=(ans*pow(prim[i],num,M))%M;
}
returnans;
}
intmain()
{
intm,n;
while(~scanf("%d%d",&m,&n),m&&n)
{
printf("%d\n",combination(m,n));
}
return0;
}
扩展资料
C语言孝启缺巧辩N项规律数和
#include"stdio.h"
#include"stdlib.h"
main()
{
intk=1,m=2;
intn,i,j;
scanf("%4d",&n);
j=1;
printf("%4d",k);
for(i=1;i<n;i++)
{
if(k==m)
{
j=-1;
m=m+1;
}
elseif(k==1)
{
j=1;
k=k+j;
printf("%4d",k);
}
printf("\n");
}
}
1、此题先构敬闭造一个求阶乘的函数,然后3次调用该函数,即可。
2、程序的源代码如下:
#include<stdio.h>
int fact(int n);
int main()
{
int m,n,c;
printf("请输入m的值:\n");
scanf("%d",&m);
printf("请输入n的值举稿并(n<=m):\n");
scanf("%d",&n);
c=fact(m)/(fact(n)*fact(m-n));
printf("请输出c的值:\n");
printf("%d\n",c);
return 0;
}
int fact(int n)//用递归求n的阶乘
{
if(n == 0 || n == 1)
return 1;
return
n*(fact(n-1));
}
3、运行结果如下,至于程正迹序的漏洞可以自己完善以提高程序的容错能力。
int f(int n)
{
int i,s=1;
for(i=2;i<枝枯=n;i++)
s*=i;
return s;
}
int main()
{ int m,n;
while(scanf("%d%d"磨轿,&m,&n))
{
printf("瞎搭肆%d\n",f(m)/(f(n)*f(m-n)));
}
return 0;
}
//祝你学习进步
int jiecheng(int x)
{
if(x==1)return 1;
else return x*jiecheng(x-1);
}
void main()
{
int m,n,c;
scanf("册正%d%d",&m,&n);
c=jiecheng(m)/(jiecheng(n)*jiecheng(m-n));
printf("c=%d"州和悔,c);
}