/// <summary> /// Computes the smallest Fibonacci number that is greater than <paramref name="number"/>. /// Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ... /// </summary> /// <param name="number">The integer we want to compute the closest Fibonacci to it that is bigger than or equal to it. </param> /// <returns>The Fibonacci number.</returns> public static FibonacciElement GetSmallestFibonacciBiggerThanNumber(int number) { var fib = new FibonacciElement(0, 1); while (fib.FibN < number) { fib.ShiftForward(); } return(fib); }
public static int Search <T>(List <T> sortedList, T key) where T : IComparable <T> { /* If key is NOT in the range, terminate search. Since the input list is sorted this early check is feasible. */ if (key.CompareTo(sortedList[0]) < 0 || key.CompareTo(sortedList[sortedList.Count - 1]) > 0) { return(-1); } FibonacciElement fib = GetSmallestFibonacciBiggerThanNumber(sortedList.Count); int startIndex = -1; /* Note that fib numbers indicate indexes in the list to look at, and not values. */ while (fib.FibN > 1) /* meaning in the sequence {0, 1, 1, 2, 3, ...} the while loop will stop when fibN = 2, thus fibN2 can at least be 1 */ { /* First compare to the value at index FibN2 */ int index = Math.Min(startIndex + fib.FibN2, sortedList.Count - 1); if (key.CompareTo(sortedList[index]) == 0) { return(index); } if (key.CompareTo(sortedList[index]) < 0) { // Shift backward twice as checked against FibN2 fib.ShiftBackward(); fib.ShiftBackward(); } if (key.CompareTo(sortedList[index]) > 0) { fib.ShiftBackward(); startIndex = index; /* Which is the previous Fib2*/ } } if (fib.FibN1 == 1 && (startIndex + 1) < sortedList.Count && sortedList[startIndex + 1].CompareTo(key) == 0) { return(startIndex + 1); } return(-1); }