Nearest Fibonacci Number to N | Java program for the above approach ; 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
class GFG { static void nearestFibonacci ( int num ) { if ( num == 0 ) { System . out . print ( 0 ) ; return ; } int first = 0 , second = 1 ; int third = first + second ; while ( third <= num ) { first = second ; second = third ; third = first + second ; } int ans = ( Math . abs ( third - num ) >= Math . abs ( second - num ) ) ? second : third ; System . out . print ( ans ) ; } public static void main ( String [ ] args ) { int N = 17 ; nearestFibonacci ( N ) ; } }