Created
October 19, 2017 11:55
-
-
Save peterhpchen/7ac0cc90d6553a7e6319e35af68af1f0 to your computer and use it in GitHub Desktop.
Pre-Test Question 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment