Saturday, 18 October 2014

Problem 15 Project Euler

Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20×20 grid?



SOLUTION:
Answer is simply C(40,20).
CODE:



int k;
int a[39];//Array for storing number from 2 to 40
int res=1;
int k;
factor(int n,int a[])//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<39)//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);}
}
}
static int result[20];
main()
{
    result[19]=1;
int i;
for(i=0;i<39;i++)
{
a[i]=40-i;
}
for(i=2;i<=20;i++)
{
    res=1;
factor(i*i,a);
}
int j;
for(i=0;i<39;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