I am learning dynamic programming and have attempted solve Problem 15 of Project Euler using dynamic programming.
Although I do know that the problem is solvable using binomial co-efficient, I wanted to see how much have I learned dynamic programming and thus tried. Here is the code:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstdlib>
using namespace std;
int main()
{
int gridsize;
cin>>gridsize;
int** grid = new int*[gridsize+1];
for ( int i = 0; i < gridsize+1; i++) {
grid[i] = new int[gridsize+1];
}
//Initialize the grid distances
for ( int i = 1; i <= gridsize ; i++) {
grid[i][0] = 1;
grid[0][i] = 1;
}
grid[0][0] = 0;
for ( int i = 1; i <= gridsize ; i++) {
for ( int j = 1; j <= gridsize ; j++) {
grid[i][j] = grid[i-1][j] + grid[i][j-1];
}
}
cout<<grid[gridsize][gridsize]<<endl;
delete(grid);
return 0;
}
The expected answer is 137846528820, while the answer that I am getting is 407575348.
Your logic is fairly correct, the problem is that you are getting a case of integer overflow. Here is a modified version of your code that works perfectly. Simply change the
intto anlong long unsignedtype.