3
I am programming a simple recursive algorithm to compute the Fibonacci sequence in R, as I do in C. Follow the same below:
fibonacci <- function (n)
{
if (n == 1L)
return (0L)
else if (n == 2L || n == 3L)
return (1L)
else
return (fibonacci(n - 1L) + fibonacci(n - 2L))
}
n <- readline(prompt="Insira um valor inteiro: ")
n <- as.integer(n)
print(fibonacci(n))
The script apparently runs smoothly in the Rstudio environment. But when running on the linux console, I get the following error:
Enter an integer value: Error in if (n == 1L) Return(0L) Else if (n == 2L || n == 3L) Return(1L) Else Return(Fibonacci(n - : missing value where TRUE/FALSE required Calls: print -> Fibonacci Execution interrupted
Could someone help me?
I can’t reproduce the error, apparently everything is fine. For safety reasons it might not be a bad idea to have the first instruction of the function
stopifnot(n > 0L)
.– Rui Barradas