Nearest Fibonacci Number to N | Function to find the Fibonacci number which is nearest to N ; Base Case ; Initialize the first & second terms of the Fibonacci series ; Store the third term ; Iterate until the third term is less than or equal to num ; Update the first ; Update the second ; Update the third ; Store the Fibonacci number having smaller difference with N ; Print the result ; Driver Code
def nearestFibonacci ( num ) : NEW_LINE INDENT if ( num == 0 ) : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT first = 0 NEW_LINE second = 1 NEW_LINE third = first + second NEW_LINE while ( third <= num ) : NEW_LINE INDENT first = second NEW_LINE second = third NEW_LINE third = first + second NEW_LINE DEDENT if ( abs ( third - num ) >= abs ( second - num ) ) : NEW_LINE INDENT ans = second NEW_LINE DEDENT else : NEW_LINE INDENT ans = third NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 17 NEW_LINE nearestFibonacci ( N ) NEW_LINE DEDENT