Número de Fibonacci más cercano a N

Dado un entero positivo N , la tarea es encontrar el número de Fibonacci más cercano al entero N dado . Si hay dos números de Fibonacci que tienen la misma diferencia de N , imprima el valor más pequeño.

Ejemplos:

Entrada: N = 20
Salida: 21
Explicación: El número de Fibonacci más cercano a 20 es 21.

Entrada: N = 17
Salida: 13

Enfoque: siga los pasos a continuación para resolver el problema:

  • Si N es igual a 0 , imprima 0 como resultado.
  • Inicialice una variable, digamos ans , para almacenar el número de Fibonacci más cercano a N .
  • Inicialice dos variables, digamos First como 0 y Second como 1 , para almacenar el primer y segundo término de la serie de Fibonacci .
  • Almacene la suma de First y Second en una variable, digamos Third .
  • Iterar hasta que el valor de Third sea como máximo N y realizar los siguientes pasos: 
    • Actualice el valor de Primero a Segundo y Segundo a Tercero .
    • Almacene la suma de Primero y Segundo en la variable Tercero .
  • Si la diferencia absoluta de Second y N es como máximo el valor de Third y N , actualice el valor de ans como Second .
  • De lo contrario, actualice el valor de ans como Third .
  • Después de completar los pasos anteriores, imprima el valor de ans como resultado.

A continuación se muestra la implementación del enfoque anterior:

C++

// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the Fibonacci
// number which is nearest to N
void nearestFibonacci(int num)
{
    // Base Case
    if (num == 0) {
        cout << 0;
        return;
    }
 
    // Initialize the first & second
    // terms of the Fibonacci series
    int first = 0, second = 1;
 
    // Store the third term
    int third = first + second;
 
    // Iterate until the third term
    // is less than or equal to num
    while (third <= num) {
 
        // Update the first
        first = second;
 
        // Update the second
        second = third;
 
        // Update the third
        third = first + second;
    }
 
    // Store the Fibonacci number
    // having smaller difference with N
    int ans = (abs(third - num)
               >= abs(second - num))
                  ? second
                  : third;
 
    // Print the result
    cout << ans;
}
 
// Driver Code
int main()
{
    int N = 17;
    nearestFibonacci(N);
 
    return 0;
}

Java

// Java program for the above approach
class GFG{
     
// Function to find the Fibonacci
// number which is nearest to N
static void nearestFibonacci(int num)
{
     
    // Base Case
    if (num == 0)
    {
        System.out.print(0);
        return;
    }
 
    // Initialize the first & second
    // terms of the Fibonacci series
    int first = 0, second = 1;
 
    // Store the third term
    int third = first + second;
 
    // Iterate until the third term
    // is less than or equal to num
    while (third <= num)
    {
         
        // Update the first
        first = second;
 
        // Update the second
        second = third;
 
        // Update the third
        third = first + second;
    }
 
    // Store the Fibonacci number
    // having smaller difference with N
    int ans = (Math.abs(third - num) >=
               Math.abs(second - num)) ?
               second : third;
 
    // Print the result
     System.out.print(ans);
}
 
// Driver Code
public static void main (String[] args)
{
    int N = 17;
     
    nearestFibonacci(N);
}
}
 
// This code is contributed by AnkThon

Python3

# Python3 program for the above approach
 
# Function to find the Fibonacci
# number which is nearest to N
def nearestFibonacci(num):
     
    # Base Case
    if (num == 0):
        print(0)
        return
 
    # Initialize the first & second
    # terms of the Fibonacci series
    first = 0
    second = 1
 
    # Store the third term
    third = first + second
 
    # Iterate until the third term
    # is less than or equal to num
    while (third <= num):
         
        # Update the first
        first = second
 
        # Update the second
        second = third
 
        # Update the third
        third = first + second
 
    # Store the Fibonacci number
    # having smaller difference with N
    if (abs(third - num) >=
        abs(second - num)):
        ans =  second
    else:
        ans = third
 
    # Print the result
    print(ans)
 
# Driver Code
if __name__ == '__main__':
     
    N = 17
     
    nearestFibonacci(N)
 
# This code is contributed by SURENDRA_GANGWAR

C#

// C# program for the above approach
using System;
 
class GFG{
 
// Function to find the Fibonacci
// number which is nearest to N
static void nearestFibonacci(int num)
{
     
    // Base Case
    if (num == 0)
    {
        Console.Write(0);
        return;
    }
 
    // Initialize the first & second
    // terms of the Fibonacci series
    int first = 0, second = 1;
 
    // Store the third term
    int third = first + second;
 
    // Iterate until the third term
    // is less than or equal to num
    while (third <= num)
    {
         
        // Update the first
        first = second;
 
        // Update the second
        second = third;
 
        // Update the third
        third = first + second;
    }
 
    // Store the Fibonacci number
    // having smaller difference with N
    int ans = (Math.Abs(third - num) >=
              Math.Abs(second - num)) ?
                       second : third;
 
    // Print the result
     Console.Write(ans);
}
 
// Driver Code
public static void Main(string[] args)
{
    int N = 17;
     
    nearestFibonacci(N);
}
}
 
// This code is contributed by sanjoy_62

Javascript

<script>
// Javascript program for the above approach
 
// Function to find the Fibonacci
// number which is nearest to N
function nearestFibonacci(num)
{
    // Base Case
    if (num == 0) {
        document.write(0);
        return;
    }
 
    // Initialize the first & second
    // terms of the Fibonacci series
    let first = 0, second = 1;
 
    // Store the third term
    let third = first + second;
 
    // Iterate until the third term
    // is less than or equal to num
    while (third <= num) {
 
        // Update the first
        first = second;
 
        // Update the second
        second = third;
 
        // Update the third
        third = first + second;
    }
 
    // Store the Fibonacci number
    // having smaller difference with N
    let ans = (Math.abs(third - num)
               >= Math.abs(second - num))
                  ? second
                  : third;
 
    // Print the result
    document.write(ans);
}
 
// Driver Code
    let N = 17;
    nearestFibonacci(N);
 
// This code is contributed by subhammahato348.
</script>
Producción: 

13

 

Complejidad temporal: O(log N)
Espacio auxiliar: O(1)

Publicación traducida automáticamente

Artículo escrito por rohitsingh07052 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *