How do you find the term X in the Fibonacci sequence?

Asked

Viewed 430 times

4

I have to do a C# program that gets a number X which will be the term of the sequence and print it on the screen.

  • 5

    What did you try?

  • Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? You need something to be improved?

1 answer

10

I was going to answer "calculating each term as far as you want". I was already thinking about making a recursive and a repetitive solution. But then I came up with the idea of looking for a better solution. And I found this in that reply in the OS (and solved by the more traditional forms as well):

using static System.Console;
using static 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) => n < 2 ? n : FibRec(n - 1) + FibRec(n - 2);
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

  • +1 for the solution that approximates the number of gold.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.