Returning Nth Fibonacci number the sequence?
Asked Answered
A

10

8

I have a question on my homework for class and I need to know how to return nth number of Fibonacci sequence using iteration (no recursion allowed).

I need some tips on how to do this so I can better understand what I am doing wrong. I output to the console in my program.cs, hence it being absent in the code below.

    // Q1)
    //
    // Return the Nth Fibonacci number in the sequence
    //
    // Input: uint n (which number to get)
    // Output: The nth fibonacci number
    //

    public static UInt64 GetNthFibonacciNumber(uint n)
    {

    // Return the nth fibonacci number based on n.


    if (n == 0 || n == 1)
        {
            return 1;
        }

        // The basic Fibonacci sequence is 
        // 1, 1, 2, 3, 5, 8, 13, 21, 34...
        // f(0) = 1
        // f(1) = 1
        // f(n) = f(n-1) + f(n-2)
        ///////////////
        //my code is below this comment

        uint a = 0;
        uint b = 1;

        for (uint i = 0; i < n; i++)
        {
            n = b + a;
            a = b;
            b = n;
        }
        return n;
Apprentice answered 22/10, 2012 at 19:20 Comment(8)
You are reusing n. That makes the loop condition wrong after the first iteration.Accoucheur
you shouldn't be modifying n in your for loop.Alms
wow i feel dumb thank you man, new to programmingApprentice
@Apprentice We've all been there. Or at least most of us.Checkoff
You should give your variables more meaningful names, rather than a, b, n, etc. It will help mitigate problems like this.Polyanthus
Are homeworks allowed on SO ? I'm pretty sure that a post has been wrote some weeks ago about this ...Mcgraw
@NisonMaël The homework tag is depricated, but homework questions are fine, they just shouldn't use the homework tag when asked.Polyanthus
@Fuji On that note, the homework tag is depricated, please don't add it to questions. See the tag wiki or this post for details.Polyanthus
C
10

:)

static ulong Fib(int n) 
{
    double sqrt5 = Math.Sqrt(5);
    double p1 = (1 + sqrt5) / 2;
    double p2 = -1 * (p1 - 1);


    double n1 = Math.Pow(p1, n + 1);
    double n2 = Math.Pow(p2, n + 1);
    return (ulong)((n1 - n2) / sqrt5);
}
Cirrhosis answered 22/10, 2012 at 19:33 Comment(6)
Nice solution, but the OP said the program should use iteration, so this does not qualify. Sorry ;-)Bouldon
@Bouldon I know, I posted this for fun.Cirrhosis
Plus, n2/sqrt5 will always be <0.5, so you can omit it and round.Reproachful
Trying to manually do this function on paper showed me just how much I've forgotten about math. Gee whiz, I feel pretty dumb now. Hehe.Nipple
Why this works: en.wikipedia.org/wiki/…Checkoff
this starts to break down as the numbers get bigger and returns incorrect results.Subdivide
C
2

Just for a little fun you could do it with an infinite Fibonacci list and some IEnumerable extensions

public IEnumerable<int> Fibonacci(){
   var current = 1;
   var b = 0;
   while(true){
       var next = current + b;
       yield return next;
       b = current;
       current = next;
   }
}

public T Nth<T>(this IEnumerable<T> seq, int n){
    return seq.Skip.(n-1).First();
}

Getting the nth number would then be

Fibonacci().Nth(n);
Chuffy answered 22/10, 2012 at 20:3 Comment(0)
E
2
        public static int GetNthFibonacci(int n)
    {
        var previous = -1;
        var current = 1;
        int index = 1;
        int element = 0;

        while (index++ <= n)
        {
            element = previous + current;
            previous = current;
            current = element;
        }

        return element;
    }
Engle answered 13/7, 2015 at 21:14 Comment(0)
A
1

I think this should do the trick:

    uint a = 0;
    uint b = 1;
    uint c = 1;

    for (uint i = 0; i < n; i++)
    {
        c = b + a;
        a = b;
        b = c;
    }
    return c;
Alms answered 22/10, 2012 at 19:26 Comment(3)
that makes fib(1) = 2. I think you should change a to 0 and c=1. That way fib(0) = c = 1, fib(1) still equals 1 and fib(2) = 2, which I believe is the correct sequenceVaivode
Why not, then, just start i at 1? He's already got a catch for 0 and 1Alms
he can remove the catches then :)Vaivode
C
0
    public IEnumerable<BigInteger> FibonacciBig(int maxn)
    {
        BigInteger Fn=1;
        BigInteger Fn_1=1;
        BigInteger Fn_2=1;

        yield return Fn;
        yield return Fn;

        for (int i = 3; i < maxn; i++)
        {
            Fn = Fn_1 + Fn_2;

            yield return Fn;

            Fn_2 = Fn_1;
            Fn_1 = Fn;
        }


    }

you can get the n-th Number by

   FibonacciBig(100000).Skip(n).First();
Cringe answered 22/10, 2012 at 19:56 Comment(0)
A
0

This is the solution for your homework, you should start from 3 because you already have numbers for f1 and f2 (first two numbers). Please note that there is no point in getting 0th Fibonacci number.

public static UInt64 GetNthFibonacciNumber(uint n)
    {

    // Return the nth fibonacci number based on n.


if (n == 1 || n == 2)
    {
        return 1;
    }


    uint a = 1;
    uint b = 1;
    uint c;

    for (uint i = 3; i <= n; i++)
    {
        c = b + a;
        a = b;
        b = c;
    }
    return c;

}

As answered 22/10, 2012 at 20:20 Comment(0)
P
0
    public static UInt64 GetNthFibonacciNumber(uint n)
    {
        if (n == 0 || n == 1)
        {
            return 1;
        }
        UInt64 a = 1, b = 1;
        uint i = 2;
        while (i <= n)
        {
            if (a > b) b += a;
            else a += b;
            ++i;
        }
        return (a > b) ? a : b;
    }
Pectase answered 7/9, 2013 at 14:53 Comment(0)
R
0
 public static List<int> PrintFibonacci(int number)
        {
            List<int> result = new List<int>();
            if (number == 0)
            {
                result.Add(0);
                return result;
            }
            else if (number == 1)
            {
                result.Add(0);
                return result;
            }
            else if (number == 2)
            {
                result.AddRange(new List<int>() { 0, 1 });
                return result;
            }
            else
            {
                //if we got thus far,we should have f1,f2 and f3 as fibonacci numbers
                int f1 = 0,
                    f2 = 1;

                result.AddRange(new List<int>() { f1, f2 });
                for (int i = 2; i < number; i++)
                {
                    result.Add(result[i - 1] + result[i - 2]);
                }
            }
            return result;

        }
Rhubarb answered 17/2, 2016 at 16:49 Comment(0)
A
0

Only 2 variables are needed (declaring one in a for loop counts too).

public int NthFib(int n)
{
    int curFib = 0;
    int nextFib = 1;
    while (--n > 0)
    {
        nextFib += curFib;
        curFib = nextFib - curFib;
    }
    return curFib;
}

If you want to see the sequence to n change it to:

public IEnumerable<int> NthFib(int n)
{
    int curFib = 0;
    int nextFib = 1;
    while (n-- > 0)
    {
        yield return curFib;
        nextFib += curFib;
        curFib = nextFib - curFib;
    }
}
Ajit answered 3/12, 2020 at 7:3 Comment(0)
F
0
   // 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,
   // 0, 1, 2, 3, 4, 5, 6,  7,  8,  9, 10, 11,  12,

    public long Fibonacci(int n)
    {
        int a = 0;

        int b = 1;

        int c = 0;

        for (int i = 0; i < n; i++)
        {
            c = a + b;
            a = b;
            b = c;
        }

        return a;
    }
Fredericafrederich answered 18/5 at 18:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.