Задача 0144

144. Послідовність чисел Фібоначчі u0, u1, … утворюється за законом u0 =0; u1 =1; ui = ui-1 + ui-2 (i = 2, 3, …).
а) Дано натуральне число n>1. Одержати u0, u1, …, un.

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                foreach (var i in Fibonacci().Take(100))
                {
                    Console.WriteLine(i);
                }
            }
            catch (OverflowException exception)
            {
                Console.WriteLine(exception.Message);
            }
        }

        private static IEnumerable<ulong> Fibonacci()
        {

            ulong prev = 1;
            ulong next = 1;
            while (true)
            {
                var sum = checked(prev + next);
                prev = next;
                next = sum;
                yield return sum;
            }
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s