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;
Servy
  • 202,030
  • 26
  • 332
  • 449
user1766351
  • 97
  • 1
  • 1
  • 4
  • 8
    You are reusing `n`. That makes the loop condition wrong after the first iteration. – harold Oct 22 '12 at 19:22
  • you shouldn't be modifying `n` in your for loop. – Shmiddty Oct 22 '12 at 19:23
  • wow i feel dumb thank you man, new to programming – user1766351 Oct 22 '12 at 19:25
  • 1
    @user1766351 We've all been there. Or at least most of us. – NullUserException Oct 22 '12 at 19:26
  • You should give your variables more meaningful names, rather than a, b, n, etc. It will help mitigate problems like this. – Servy Oct 22 '12 at 19:32
  • Are homeworks allowed on SO ? I'm pretty sure that a post has been wrote some weeks ago about this ... – Maël Nison Oct 22 '12 at 19:42
  • @NisonMaël The homework tag is depricated, but homework questions are fine, they just shouldn't use the homework tag when asked. – Servy Oct 22 '12 at 19:51
  • @Fuji On that note, the homework tag is depricated, please don't add it to questions. See the tag wiki or [this post](http://meta.stackexchange.com/questions/147100/the-homework-tag-is-now-officially-deprecated) for details. – Servy Oct 22 '12 at 19:52

9 Answers9

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);
}
L.B
  • 114,136
  • 19
  • 178
  • 224
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);
Rune FS
  • 21,497
  • 7
  • 62
  • 96
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;
    }
Rajnikant
  • 2,176
  • 24
  • 23
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;
Nabou
  • 549
  • 2
  • 7
  • 16
Shmiddty
  • 13,847
  • 1
  • 35
  • 52
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();
user287107
  • 9,286
  • 1
  • 31
  • 47
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;

}

Nikola Davidovic
  • 8,556
  • 1
  • 27
  • 33
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;
    }
Gevorg M
  • 51
  • 4
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;

        }
dotnetdev_2009
  • 722
  • 1
  • 11
  • 28
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;
    }
}
Clay Ver Valen
  • 1,033
  • 6
  • 10