2
public int Fibonacci(int x)
{        
    int prev = -1;
    int next = 1;
    for (int i = 0; i < x; i++)
    {
        int sum = prev + next;
        prev = next;
        next = sum;
        Console.WriteLine(sum); 
    }
    return sum; // plz teel me how can i return whole list ??
}

How can i return whole output of above series? i.e. if x=3 then 0 1 1 2 so how can i return it?

moinudin
  • 134,091
  • 45
  • 190
  • 216
Neo
  • 15,491
  • 59
  • 215
  • 405
  • Array, out parameters, ref parameter, custom object - anyone – pavanred Dec 30 '10 at 16:51
  • I'm counting the minutes till the first one comes up with a C# version of the famous Haskell one: `fibs = 0 : 1 : zipWith (+) fibs (tail fibs)`. Or in Scala: `lazy val fibs: Stream[BigInt] = 0 #:: 1 #:: fibs.zip(fibs.tail).map { case (a, b) => a + b }`. – Jörg W Mittag Dec 30 '10 at 19:06
  • Jörg W Mittag: that code is Hollywood-material, but that won't still be able to beat this: http://stackoverflow.com/questions/1995113/sci-fi-action-movie-programming-language/2003939#2003939 – Michael Buen Dec 31 '10 at 05:56

8 Answers8

21

Try this:

public IEnumerable<int> Fibonacci(int x)
{
    int prev = -1;
    int next = 1;
    for (int i = 0; i < x; i++)
    {
       int sum = prev + next;
       prev = next;
       next = sum;
       yield return sum;
    }
}
Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
  • 1
    +1 for having the only answer that is not the EXACT SAME as the others (and also correct) – rownage Dec 30 '10 at 16:55
  • @rownage: all the answers around at this time are different from each other. Look at the return types. – R. Martinho Fernandes Dec 30 '10 at 16:56
  • @Marty: You also missed that they named their variables differently. Sarcasm aside, look at the same nine lines of code inside the methods. It is a simple enough problem that many people will have the same correct answer, which is why I enjoyed this answer in particular for taking a unique approach. – rownage Dec 30 '10 at 17:49
  • my code http://stackoverflow.com/questions/4564472/how-can-i-return-a-fibonacci-series-should-i-use-ilist/4567270#4567270 is different, doesn't know that -1 is the *intuitive* (basing on how most answers ended up here look identical) way to start the fibonacci logic. i feel different(on both senses of the word, but more on the good side [xkcd 541 here]) – Michael Buen Jan 01 '11 at 02:23
  • For more fun, take away the argument... just loop forever, and let the caller use the `.Take()` extension method to bound the sequence. – Joel Coehoorn Jul 04 '19 at 15:06
5

This will calculate the whole list and return it after finishing (eager evaluation):

public IEnumerable<int> Fibonacci(int x)
{
    IList<int> fibs = new List<int>();

    int prev = -1; // previous val
    int next = 1;
    for (int i = 0; i < x; i++)
    {
     int sum = prev + next;
        prev = next;
        next = sum;
        fibs.Add(sum); 
    }

    return fibs;
}

This will calculate each item and return it as it is needed (lazy evaluation), using yield:

public IEnumerable<int> Fibonacci(int x)
{
    int prev = -1;
    int next = 1;
    for (int i = 0; i < x; i++)
    {
     int sum = prev + next;
        prev = next;
        next = sum;
        yield return sum;
    }
}
navule
  • 3,212
  • 2
  • 36
  • 54
Oded
  • 489,969
  • 99
  • 883
  • 1,009
0

I should say that first answer is enough but if you have big numbers, you will have overflow with int. Instead try to use ulong; we need to update that to not use -1 on prev because you cant use negatives. Instead you can try this one:

 public static IEnumerable<ulong> Generate(ulong n)
    {
        if (n < 1) yield break;
        yield return 1;
        ulong prev = 0;
        ulong next = 1;

        for (ulong i = 1; i < n; i++)
        {
            ulong sum = prev + next;
            prev = next;
            next = sum;
            yield return sum;
        }
    }

where for the first number returns 1, and more than that makes the Fibonacci using previous calculation returning positive numbers on ulong format.

gds03
  • 1,349
  • 3
  • 18
  • 39
0
static IEnumerable<int> Fibonacci(int n)
    {
        int a = 0, b = 1;
        yield return a;
        yield return b;
        for (int i = 0; i < n; i++)
        {
            yield return a = a + b;
            yield return b = b + a;
        }
    }
0

You return one by... returning one. It's not complicated.

public IList<int> Fibonacci(int x)
{
    List<int> result = new List<int>();

    int prev = -1;
    int next = 1;
    for (int i = 0; i < x; i++)
    {
     int sum = prev + next;
        prev = next;
        next = sum;
        result.Add(sum);
    }

    return result;
}
Jonathan Grynspan
  • 43,286
  • 8
  • 74
  • 104
0

If you want to return like a list or an array of all of their numbers, you would just need something like this:

public List<int> Fibonacci(int x)
{   
    List<int> returnList = new List<int>();

    int prev = -1;
    int next = 1;
    for (int i = 0; i < x; i++)
    {
        int sum = prev + next;
        prev = next;
        next = sum;
        returnList.Add(sum);
    }
    return returnList; 
}
Rion Williams
  • 74,820
  • 37
  • 200
  • 327
0

I am inspired by Andrew Hare's lazy loading fibonacci to rewrite my fibonacci before http://www.ienablemuch.com/2010/09/fibonacci-using-sql.html to lazy loading approach:

using System;
using System.Collections.Generic;

using System.Linq;

namespace Fibonacci
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            Console.WriteLine("Sans list. Lazy load stuff:");
            int i = 0;


            foreach(int n in Fibonacci().Take(10))
            {
                ++i;
                Console.WriteLine("Loading {0} {1}", i, n);             
            }


            Console.WriteLine("\nPick the 20th fibonacci:");
            Console.WriteLine("\n20th fibonacci: {0}", 
                 Fibonacci().Skip(20 - 1).Take(1).Single());


            Console.WriteLine("\nEagerly load everything in list:");
            i = 0;      
            foreach(int n in Fibonacci().Take(10).ToList())
            {
                ++i;
                Console.Write("\nEager loading {0} {1}", i, n);
            }

        }



        static IEnumerable<int> Fibonacci()
        {
         int a = 0,  b = 1;

         for(;;)
         {
          Console.Write("Lazy");         
          yield return a;
          int n = a;
          a += b;
          b = n;          
         }


        }
    }//class

}

Output:

Sans list. Lazy load stuff:
LazyLoading 1 0
LazyLoading 2 1
LazyLoading 3 1
LazyLoading 4 2
LazyLoading 5 3
LazyLoading 6 5
LazyLoading 7 8
LazyLoading 8 13
LazyLoading 9 21
LazyLoading 10 34

Pick the 20th fibonacci:
LazyLazyLazyLazyLazyLazyLazyLazyLazyLazyLazyLazyLazyLazyLazyLazyLazyLazyLazyLazy
20th fibonacci: 4181

Eagerly load everything in list:
LazyLazyLazyLazyLazyLazyLazyLazyLazyLazy
Eager loading 1 0
Eager loading 2 1
Eager loading 3 1
Eager loading 4 2
Eager loading 5 3
Eager loading 6 5
Eager loading 7 8
Eager loading 8 13
Eager loading 9 21
Eager loading 10 34

At least this solution differs from others :-) this doesn't start with -1, one can use unsigned int instead of int

Michael Buen
  • 38,643
  • 9
  • 94
  • 118
-1
            int n = 15; 
           string r = string.Empty;
            int s=0, t=1,u;
            for (int i = 0; i < n; i++)
            {
                if (i == 0)
                {                  
                    r += Convert.ToString(s)+Convert.ToString(t);  
                }
                else
                {
                    u = s + t;
                    s = t;
                    t = u;
                    r += Convert.ToString(u);                                         
                }
            }
            MessageBox.Show(r);
Pradeep
  • 189
  • 1
  • 5
  • 16