一週間で身につくC# の勉強中11

prob8-10

1,1から始まり、前の2つの値の和を次の値とする数列のことを、フィボナッチ数列という(以下の例を参照)。このとき、40までのフィボナッチ数列を求めてint型の配列に代入し、表示しなさい。

例 1  1  2  3  5  8  13  …

考え方のポイント

問題を長さ40の配列と考えて解いています。配列0,1だけ特殊な数字なのでそれ以降の配列だけforに入れています。一つ前の数hi[i-1]+二つ前の数hi[i-2]で配列に入れる数がでます。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace prob8_10
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] hi = new int[40];
            hi[0] = 1;
            hi[1] = 1;
            for(int i= 2; i < 40; i++)
            {
                hi[i] = hi[i-2]+hi[i-1];
            }
            foreach (int i in hi)
            {
                Console.Write("{0} ", i);
            }
        }
    }
}

問題の意味が40の数字までということなら

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace prob8_10_2
{
    class Program
    {
        static void Main(string[] args)
        {
            int mae1 = 1;
            int mae2 = 1;
            int kazu = 0;
            int cnt = 2;
            while (mae1 + mae2 <= 40)
            {
                kazu = mae1 + mae2;
                mae2 = mae1;
                mae1 = kazu;
                cnt++;
            }
            int[] hi = new int[cnt];
            hi[0] = 1;
            hi[1] = 1;
            for (int i = 2; i < cnt; i++)
            {
                hi[i] = hi[i - 2] + hi[i - 1];
            }
            foreach (int i in hi)
            {
                Console.Write("{0} ", i);
            }
        }
    }
}

40以下の数字が何個になるか調べてから配列の長さを決めています。