I made various Fibonacci sequence functions (Ruby)

Write with simple recursion

Absolutely slow (because it recurses until n reaches a depth of 0 or 1).

def fib(n)
    return n if n == 0 || n == 1
    return fib(n - 1) + fib(n - 2)
end

A little ingenious recursion

It's recursion, but what you're doing isn't much different from a for statement. It's just a recursive function, so if a super big n is passed, it may overflow the stack?

def fib(n, a, b)
    return a if n == 0
    return fib(n - 1, b, a + b)
end

Write with for

Since it is not recursion, stack overflow will not occur ... You can write beautifully by using split assignment. This is a split assignment.

def fib(n)
    a, b = 0, 1
    n.times.each { a, b = b, a + b }
    a
end

Write with dynamic programming (memoization)

TODO Please write someone.

Recommended Posts

I made various Fibonacci sequence functions (Ruby)
Collatz number, Fibonacci number, triangular number I tried to make various sequence programs
[Ruby] I made a simple Ping client
I made a risky die with Ruby
I made StringUtils.isBlank
I started Ruby
I made blackjack with Ruby (I tried using minitest)
I made a Ruby extension library in C
I made a portfolio with Ruby On Rails
[Ruby] I made a crawler with anemone and nokogiri.
Various Ruby string operations
I made an interpreter (compiler?) With about 80 lines in Ruby.
I updated my own blackjack made with Ruby for my portfolio
I want to implement various functions with kotlin and java!