Recuento de pares de Fibonacci con suma N en el rango de 0 a N

Dado un número N , la tarea es encontrar el recuento de pares de Fibonacci en el rango de 0 a N cuya suma es N.

Ejemplos: 

Entrada: N = 90 
Salida:
Explicación: 
Solo el par de Fibonacci en el rango [0, 90] cuya suma es igual a 90 es {1, 89}

Entrada: N = 3 
Salida:
Explicación: 
Par de Fibonacci en el rango [0, 3] cuya suma es igual a 3 son {0, 3}, {1, 2} 

Acercarse: 

  1. La idea es usar hashing para precalcular y almacenar los números de Fibonacci menores que iguales a N en un hash
  2. Inicializar una variable de contador como 0
  3. Luego, para cada elemento K en ese hash, verifique si N – K también está presente en el hash.
  4. Si tanto K como N – K están en hash, incremente la variable de contador

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

C++

// C++ program to find count of
// Fibonacci pairs whose
// sum can be represented as N
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to create hash table
// to check Fibonacci numbers
void createHash(set<int>& hash, int maxElement)
{
    // Storing the first two numbers
    // in the hash
    int prev = 0, curr = 1;
    hash.insert(prev);
    hash.insert(curr);
 
    // Finding Fibonacci numbers up to N
    // and storing them in the hash
    while (curr < maxElement) {
 
        int temp = curr + prev;
        hash.insert(temp);
        prev = curr;
        curr = temp;
    }
}
 
// Function to find count of Fibonacci
// pair with the given sum
int findFibonacciPairCount(int N)
{
    // creating a set containing
    // all fibonacci numbers
    set<int> hash;
    createHash(hash, N);
 
    // Initialize count with 0
    int count = 0;
 
    // traverse the hash to find
    // pairs with sum as N
    set<int>::iterator itr;
    for (itr = hash.begin();
 *itr <= (N / 2);
 itr++) {
 
        // If both *itr and
//(N - *itr) are Fibonacci
        // increment the count
        if (hash.find(N - *itr)
 != hash.end()) {
 
            // Increase the count
            count++;
        }
    }
 
    // Return the count
    return count;
}
 
// Driven code
int main()
{
    int N = 90;
    cout << findFibonacciPairCount(N)
<< endl;
 
    N = 3;
    cout << findFibonacciPairCount(N)
 << endl;
 
    return 0;
}

Java

// Java program to find count of
// Fibonacci pairs whose
// sum can be represented as N
import java.util.*;
 
class GFG{
  
// Function to create hash table
// to check Fibonacci numbers
static void createHash(HashSet<Integer> hash, int maxElement)
{
    // Storing the first two numbers
    // in the hash
    int prev = 0, curr = 1;
    hash.add(prev);
    hash.add(curr);
  
    // Finding Fibonacci numbers up to N
    // and storing them in the hash
    while (curr < maxElement) {
  
        int temp = curr + prev;
        hash.add(temp);
        prev = curr;
        curr = temp;
    }
}
  
// Function to find count of Fibonacci
// pair with the given sum
static int findFibonacciPairCount(int N)
{
    // creating a set containing
    // all fibonacci numbers
    HashSet<Integer> hash = new HashSet<Integer>();
    createHash(hash, N);
  
    // Initialize count with 0
    int count = 0;
    int i = 0;
 
    // traverse the hash to find
    // pairs with sum as N
    for (int itr : hash) {
        i++;
        
        // If both *itr and
        //(N - *itr) are Fibonacci
        // increment the count
        if (hash.contains(N - itr)) {
  
            // Increase the count
            count++;
        }
        if(i == hash.size()/2)
            break;
    }
  
    // Return the count
    return count;
}
  
// Driven code
public static void main(String[] args)
{
    int N = 90;
    System.out.print(findFibonacciPairCount(N)
+"\n");
  
    N = 3;
    System.out.print(findFibonacciPairCount(N)
 +"\n");
  
}
}
 
// This code is contributed by PrinciRaj1992

Python3

# Python3 program to find count of
# Fibonacci pairs whose sum can be
# represented as N
 
# Function to create hash table
# to check Fibonacci numbers
def createHash(Hash, maxElement):
     
    # Storing the first two numbers
    # in the hash
    prev, curr = 0, 1
    Hash.add(prev)
    Hash.add(curr)
    
    # Finding Fibonacci numbers up to N
    # and storing them in the hash
    while (curr < maxElement):
        temp = curr + prev
        Hash.add(temp)
        prev = curr
        curr = temp
    
# Function to find count of Fibonacci
# pair with the given sum
def findFibonacciPairCount(N):
     
    # Creating a set containing
    # all fibonacci numbers
    Hash = set()
    createHash(Hash, N)
    
    # Initialize count with 0
    count = 0
    i = 0
   
    # Traverse the hash to find
    # pairs with sum as N
    for itr in Hash:
        i += 1
          
        # If both *itr and 
        #(N - *itr) are Fibonacci
        # increment the count
        if ((N - itr) in Hash):
             
            # Increase the count
            count += 1
         
        if (i == (len(Hash) // 2)):
            break
    
    # Return the count
    return count
     
# Driver Code
N = 90
print(findFibonacciPairCount(N))
 
N = 3
print(findFibonacciPairCount(N))
 
# This code is contributed by divyeshrabadiya07

C#

// C# program to find count of
// Fibonacci pairs whose
// sum can be represented as N
using System;
using System.Collections.Generic;
 
class GFG{
   
// Function to create hash table
// to check Fibonacci numbers
static void createHash(HashSet<int> hash, int maxElement)
{
    // Storing the first two numbers
    // in the hash
    int prev = 0, curr = 1;
    hash.Add(prev);
    hash.Add(curr);
   
    // Finding Fibonacci numbers up to N
    // and storing them in the hash
    while (curr < maxElement) {
   
        int temp = curr + prev;
        hash.Add(temp);
        prev = curr;
        curr = temp;
    }
}
   
// Function to find count of Fibonacci
// pair with the given sum
static int findFibonacciPairCount(int N)
{
    // creating a set containing
    // all fibonacci numbers
    HashSet<int> hash = new HashSet<int>();
    createHash(hash, N);
   
    // Initialize count with 0
    int count = 0;
    int i = 0;
  
    // traverse the hash to find
    // pairs with sum as N
    foreach (int itr in hash) {
        i++;
         
        // If both *itr and
        //(N - *itr) are Fibonacci
        // increment the count
        if (hash.Contains(N - itr)) {
   
            // Increase the count
            count++;
        }
        if(i == hash.Count/2)
            break;
    }
   
    // Return the count
    return count;
}
   
// Driven code
public static void Main(String[] args)
{
    int N = 90;
    Console.Write(findFibonacciPairCount(N)
                    +"\n");
   
    N = 3;
    Console.Write(findFibonacciPairCount(N)
                     +"\n");
   
}
}
 
// This code is contributed by PrinciRaj1992

Javascript

<script>
 
// Javascript program to find count of
// Fibonacci pairs whose
// sum can be represented as N
 
// Function to create hash table
// to check Fibonacci numbers
function createHash(hash, maxElement)
{
    // Storing the first two numbers
    // in the hash
    var prev = 0, curr = 1;
    hash.add(prev);
    hash.add(curr);
 
    // Finding Fibonacci numbers up to N
    // and storing them in the hash
    while (curr < maxElement) {
 
        var temp = curr + prev;
        hash.add(temp);
        prev = curr;
        curr = temp;
    }
}
 
// Function to find count of Fibonacci
// pair with the given sum
function findFibonacciPairCount(N)
{
    // creating a set containing
    // all fibonacci numbers
    var hash = new Set();
    createHash(hash, N);
 
    // Initialize count with 0
    var count = 0, i =0;
 
    // traverse the hash to find
    // pairs with sum as N
    hash.forEach(element => {
        i++;
 
        if(hash.size >= parseInt(i*2))
        {
         
        // If both *itr and
        //(N - *itr) are Fibonacci
        // increment the count
        if (hash.has(N-element))
        {
 
            // Increase the count
            count++;
        }
        }
 
    });
 
    // Return the count
    return count;
}
 
// Driven code
var N = 90;
document.write( findFibonacciPairCount(N) + "<br>")
N = 3;
document.write( findFibonacciPairCount(N) + "<br>")
 
// This code is contributed by rrrtnx.
</script>
Producción: 

1
2

 

Análisis de rendimiento: 

  • Complejidad de tiempo: en el enfoque anterior, la creación de un mapa hash de números de Fibonacci menores que N sería una operación O (N) . Luego, para cada elemento en hashmap, buscamos otro elemento haciendo que la complejidad del tiempo de búsqueda sea O(N * log N) . Entonces, la complejidad del tiempo total es O (N * log N)
  • Complejidad del espacio auxiliar: en el enfoque anterior, estamos usando espacio adicional para almacenar valores de hashmap. Entonces la complejidad del espacio auxiliar es O(N)

Publicación traducida automáticamente

Artículo escrito por Code_r 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 *