text: Nearest Fibonacci Number to N | C ++ 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
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; void nearestFibonacci ( int num ) { if ( num == 0 ) { cout << 0 ; return ; } int first = 0 , second = 1 ; int third = first + second ; while ( third <= num ) { first = second ; second = third ; third = first + second ; } int ans = ( abs ( third - num ) >= abs ( second - num ) ) ? second : third ; cout << ans ; } int main ( ) { int N = 17 ; nearestFibonacci ( N ) ; return 0 ; }