peterhpchen
10/19/2017 - 11:55 AM

Pre-Test Question 3

Pre-Test Question 3

using System;

namespace Question3
{
    public class Class1
    {
        //要檢查的最大Fibonacci的N, 題目為60
        private static int MAXNOFFIBONACCI = 60;

        public int[] nextFibonacci(int[] numArray)
        {
            int lengthOfNumArray = numArray.Length;
            int[] result = new int[lengthOfNumArray];
            //用個陣列紀錄已算過的數,避免重算
            int[] fibonacciArray = new int[MAXNOFFIBONACCI];
            fibonacciArray[index(1)] = 1;
            fibonacciArray[index(2)] = 1;

            for (int i = 0; i < lengthOfNumArray; i++)
            {
                for (int j = index(2); j < MAXNOFFIBONACCI; j++)
                {
                    //沒有算過計算之後塞進陣列中
                    if (fibonacciArray[j] == 0) fibonacciArray[j] = fibonacciArray[j - 1] + fibonacciArray[j - 2];
                    //目前的Fibonacci小於目標數的話要繼續找
                    if (fibonacciArray[j] <= numArray[i]) continue;
                    //大於的話塞到result中
                    result[i] = fibonacciArray[j];
                    break;
                }
            }

            return result;
        }

        private int index(int n)
        {
            return n - 1;
        }
    }
}