Test if a number is fibonacci

后端 未结 20 944
深忆病人
深忆病人 2020-11-30 17:58

I know how to make the list of the Fibonacci numbers, but i don\'t know how can i test if a given number belongs to the fibonacci list - one way that comes in mind is genera

20条回答
  •  星月不相逢
    2020-11-30 18:20

    This is my solution I'm not sure if it benchmarks. I hope this helps!

    def is_fibonacci?(i)
      a,b=0,1
        until b >= i
            a,b=b,a+b
            return true if b == i
        end
    end
    

    what a,b=b,a+b is doing

     0, 1 = 1, 0 +1
     1, 1 = 1, 1 + 1
     1, 2 = 2, 1 + 2
     2, 3 = 3, 2 + 3
    
    fib1 = fib2
    fib2 = fib1 + fib2
    

提交回复
热议问题