class Integer def mod_exp(exp, mod) exp < 0 and raise ArgumentError, "negative exponent" prod = 1 base = self % mod until exp.zero? exp.odd? and prod = (prod * base) % mod exp >>= 1 base = (base * base) % mod end prod end end PHI = (1 + Math.sqrt(5)) / 2 def fib(n) ((PHI ** n - (-1 / PHI) ** n) / Math.sqrt(5)).to_i end puts fib(8)