Home > Blockchain >  Using recursive function in R [Error C stack usage too close to limit]
Using recursive function in R [Error C stack usage too close to limit]

Time:12-01

I have to use a recursive function to find the sum of positive integers \sum_{n}^{2n-1}k . I attempted to use the idea where \sum_{n}^{2n-1}k = \sum_{1}^{2n-1}k - \sum_{1}^{n-1}k Hence, this is my attempt at coding using recursive function. Code:

penta_recur=function(n){
x = 2*n - 1
y = n - 1
if (n == 1){
return(1)
} else {
return(x penta_recur(x-1)-y-penta_recur(y-1))
} 
}

However, my output is an error:

Error: C stack usage  15923328 is too close to the limit

Is there a way to resolve my issue? I think the problem is definitely something to do with the 2nd return line which caused me to screw up the entire code.

CodePudding user response:

Hi i guess I have the answer to my question. The code that I typed:

P_n=function(n){
x=(3*n^2-n)/2
if(n == 0){
return (0)
}else{
return(x)
}
}

I guess I should have been more specific with the title where I wanted to find the pentagonal number given an n positive integer. Thanks for the help. Although I wonder if this counts as an recursive function. Any opinion on this solution

  • Related