Saturday, 18 October 2014

A program for finding combinations

int res=1;
int k;
factor(int n,int a[],int numn)//function to find factors of a number
{
    if(res==1){k=n;}
int i,j;
for(i=2;i<=n;i++)
{
if(n%i==0&&res!=k)
{
    int j=0;
   while(j<numn)//loop to divide the factors of number by any number divisible by factor in array
   {
       if(a[j]%i==0){a[j]/=i;break;}
   j++;
   }

   res*=i;factor(n/i,a,numn);}
}
}
static int result[20];
main()
{
printf("C(n,r)\n");
printf("Please Enter n\n");
int numn;
scanf("%d",&numn);
int a[numn];//Array for storing number from 2 to numn
printf("\nPlease Enter r\n");
int r;
scanf("%d",&r);
if(numn<r){printf("0");exit(0);}
    result[19]=1;
int i;
for(i=0;i<numn;i++)
{
a[i]=numn-i;
}
for(i=2;i<=r;i++)
{
    res=1;
factor(i,a,numn);
}
for(i=2;i<=numn-r;i++)
{
    res=1;
factor(i,a,numn);
}

int j;
for(i=0;i<numn;i++)
{
for(j=0;j<20;j++)
{
    result[j]*=a[i];
}
for(j=19;j>=0;j--)
{
    if(result[j]>9)
    {
        int k=result[j];
        int index=j;
        result[index--]=k%10;
        k/=10;
        while(k!=0)
        {
        result[index--]+=(k%10);
        k/=10;
        }
    }
}
}
for(j=0;j<20;j++)
{
    printf("%d",result[j]);
}
}

No comments:

Post a Comment