Recursion: Fibonacci Numbers

  • + 0 comments

    without a loop in C#, so O(1) time and complexity https://math.stackexchange.com/questions/90821/how-to-find-the-closed-form-to-the-fibonacci-numbers

    using System;
    using System.Collections.Generic;
    using System.IO;
    
    class Solution {
    
        public static int Fibonacci(int n) {
            double sqrt_5 = Math.Sqrt(5);
            double inv_sqrt_5 = 1 / sqrt_5;
            double part_one = inv_sqrt_5 * Math.Pow((1 + sqrt_5) / 2, n);
            double part_two = inv_sqrt_5 * Math.Pow((1 - sqrt_5) / 2, n);
            return Convert.ToInt32(part_one - part_two);
        }
    
            static void Main(String[] args) {
                    int n = Convert.ToInt32(Console.ReadLine());
                    Console.WriteLine(Fibonacci(n));
            }
    }