Friday 27 September 2013

Why am I getting Stack Overflow error in Recursive C program while computing elements of pascal triangle?

Why am I getting Stack Overflow error in Recursive C program while
computing elements of pascal triangle?

I am writing a C program to compute (i,j)th element in Pascular Triangle
i.e f(n,1) = f(n,n) = n, and f(n,k) = f(n-1,k) + f(n-1,k-1) for 1 < k < n
I need to print value modulo 1000000007. The Code follows :
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
unsigned long returnModPascal(unsigned long n,unsigned long k);
int main()
{
int t;
unsigned long int ans,n,k;
scanf("%d",&t);
while(t--)
{
scanf("%lu %lu",&n,&k);
ans=returnModPascal(n,k);
printf("%lu",ans);
}
return 0;
}
unsigned long int returnModPascal(unsigned long int n,unsigned long int k)
{
unsigned long int tempans,tempans1,tempans2;
if(k==1 || k==n)
tempans=n;
else
{
tempans1=returnModPascal(n-1,k);
if (tempans1>=1000000007)
tempans1=tempans1%1000000007;
tempans2=returnModPascal(n-1,k-1);
if (tempans2>=1000000007)
tempans2=tempans2%1000000007;
if (tempans1+tempans2>=1000000007)
tempans=tempans1+tempans2-1000000007;
else
tempans=tempans1+tempans2;
}
return tempans;
}
When i give input for example 123456 3 as n & k Error is coming
Unhandled exception at 0x003C3D79 in DummyProject.exe: 0xC00000FD: Stack
overflow (parameters: 0x00000001, 0x003D2F70).
Any Help is appreciated.

No comments:

Post a Comment