• + 0 comments

    Since this problem is such a basic introduction to recursion, I like to go against the grain and like solving it without recursion. This problem can be trivialized with a little mathematical insight. Binet's formula is a formula for calculating the nth fibonacci number.

    return ((pow(((1+sqrt(5))/2),x-1)-pow(((1-sqrt(5))/2),x-1))/sqrt(5)).toInt
    

    In a mathematically perfect universe the function would always output an integer, but due to floating point error it will usually be a little off. Rounding it to the nearest integer will solve this issue for all practical purposes (I have a hunch that if the input is allowed to be arbitrarily large then the error might make it round to the wrong int, but the input would probably be far outside any range one would reasonably be working with at that point).