问题
I wrote some code to calculate the Nth catalan number. However, it isn't returning the correct result when N=20 and onwards. The results when N<20 is correct though, so I'm not sure what is wrong.
So, when N=20, its supposed to return 6564120420, but it returns 2269153124 for me.
Can someone point me in the right direction?
#include <iostream>
using namespace std;
unsigned long int countTree(unsigned int N)
{
//used to store catalan numbers
unsigned long int catalan[N+1];
//N(0)=N(1)=1
catalan[0]=catalan[1]=1;
int i,j;
for(i=2;i<=N;i++)
{
catalan[i]=0;
for(j=0;j<i;j++)
{
catalan[i]+=catalan[j]*catalan[i-j-1];
}
}
return catalan[N];
}
int main()
{
unsigned int x;
cout<<"Input N:"<<endl;
cin>>x;
unsigned long int result=countTree(x);
cout<<result<<endl;
return 0;
}
回答1:
You're exceeding the maximum size those variable types let you store.
The long long
type is your best bet.
You can have a look here on what the max values for different types of integers are: http://www.cplusplus.com/reference/climits/
回答2:
use "unsigned long long" in place of "unsigned int".`
#include <iostream>
using namespace std;
unsigned long long countTree(unsigned int N)
{
//used to store catalan numbers
unsigned long long catalan[N+1];
catalan[0]=catalan[1]=1;
int i,j;
for(i=2;i<=N;i++)
{
catalan[i]=0;
for(j=0;j<i;j++)
catalan[i]+=catalan[j]*catalan[i-j-1];
}
return catalan[N];
}
int main()
{
unsigned int x;
cout << "Input N:" << endl;
cin >> x;
cout << countTree(x) << endl;
return 0;
}
来源:https://stackoverflow.com/questions/25539844/calculate-the-nth-catalan-number