How to find the term X of the Fibonacci sequence?

4

I have to make a program in C # that receives a% number of% that will be the term of the sequence and print it on the screen.

    
asked by anonymous 16.03.2015 / 00:23

1 answer

9

I was going to answer "calculating each term as far as you want". I was already thinking of doing a recursive and a repetitive solution. But then I came up with the idea of looking for someone who had already thought of a better solution. And I found this in that answer in the SO (and I solved the more traditional ones as well):

using System.Console;
using System.Math;

public class Program {
    public static void Main() {
        for (int i = 0; i < 20; i++) {
            WriteLine($"{Fib(i)}, {FibIte(i)}, {FibRec(i)}");
        }
    }
    static int Fib(int n) {
        double sqrt5 = Sqrt(5);
        double p1 = (1 + sqrt5) / 2;
        double p2 = -1 * (p1 - 1);
        return (int)((Pow(p1, n) - Pow(p2, n)) / sqrt5);
    }
    static int FibIte(int n) {
        int a = 0;
        int b = 1;
        for (int i = 0; i < n; i++) {
            int temp = a;
            a = b;
            b = temp + b;
        }
        return a;
    }
    static int FibRec(int n) {
        return n < 2 ? n : FibRec(n - 1) + FibRec(n - 2);
    }
}

See running on dotNetFiddle .

    
16.03.2015 / 00:32