Open In App

Smallest Fibonacci Product from Array elements

Last Updated : 11 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of integers, find the smallest Fibonacci number that can be formed by selecting any two distinct numbers from the array and multiplying them. If no such number exists, return -1.

Examples:

Input: arr[] = {1, 2, 3, 4, 5}
Output: 2
Explanation: The possible pairs of distinct numbers from the array are: (1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5). The products of each of these pairs are: 2, 3, 4, 5, 6, 8, 10, 12, 15, 20. Out of these products, the only Fibonacci numbers are 2, 3, 5, and 8. The smallest of these is 2, the answer we need to return.

Input: arr[] = {3, 7, 10, 15, 22}
Output: 21
Explanation: The possible pairs of distinct numbers from the array are: (3, 7), (3, 10), (3, 15), (3, 22), (7, 10), (7, 15), (7, 22), (10, 15), (10, 22), (15, 22). The products of each of these pairs are 21, 30, 45, 66, 70, 105, 154, 150, 220, 330. The smallest Fibonacci number is 21, the answer we need to return.

Input: arr[] = {4, 6, 8, 10}
Output: -1
Explanation: The possible pairs of distinct numbers from the array are: (4, 6), (4, 8), (4, 10), (6, 8), (6, 10), (8, 10). The products of each of these pairs are 24, 32, 40, 48, 60, and 80. None of these products are Fibonacci numbers, so no Fibonacci number can be formed by multiplying any two distinct numbers from the given array.

Approach: To solve the problem follow the below idea:

The approach efficiently finds the smallest Fibonacci number that can be formed by multiplying two distinct integers from an input array. It does so by leveraging the property that a number is a Fibonacci number if and only if one of (5 * num^2 + 4) or (5 * num^2 – 4) is a perfect square. The code iterates through all pairs of distinct numbers in the array, calculates their product, and checks if it’s a Fibonacci number using this property. If found, it updates the minimum Fibonacci product.

Steps of the above approach:

  • Define helper functions: isPerfectSquare to check if a number is a perfect square and isFibonacci to check if a number is a Fibonacci number.
  • Define the findSmallestFibonacciProduct function, which takes a vector of integers as input.
  • Initialize variables: n to store the size of the input array and minFibProduct to keep track of the smallest Fibonacci product, initially set to a large value.
  • Iterate through all pairs of distinct numbers in the input array using nested loops.
  • Calculate the product of the current pair of numbers.
  • Check if the product is a Fibonacci number using the isFibonacci function. If it is, update minFibProduct if the current product is smaller.
  • Continue checking all possible pairs of numbers in the array.
  • After checking all pairs, if minFibProduct is still at its initial value, return -1, indicating that no Fibonacci product was found.
  • Otherwise, return the smallest Fibonacci product found in the array.

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
// Function to check if a number
// is a perfect square
bool isPerfectSquare(int x)
{
    int s = sqrt(x);
    return (s * s == x);
}
 
// Function to check if a number
// is a Fibonacci number
bool isFibonacci(int num)
{
    return isPerfectSquare(5 * num * num + 4)
           || isPerfectSquare(5 * num * num - 4);
}
 
// Function to find the smallest Fibonacci
// product from distinct pairs in an array
int findSmallestFibonacciProduct(vector<int>& arr)
{
    int n = arr.size();
    int minFibProduct = INT_MAX;
 
    // Iterate through all pairs of distinct
    // numbers in the array
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            int product = arr[i] * arr[j];
 
            // Check if the product is a
            // Fibonacci number
            if (isFibonacci(product)) {
                minFibProduct = min(minFibProduct, product);
            }
        }
    }
 
    // If no Fibonacci product is found, return
    // -1; otherwise, return the smallest one
    if (minFibProduct == INT_MAX) {
        return -1;
    }
 
    return minFibProduct;
}
 
// Drivers code
int main()
{
 
    // Example input arrays
    vector<int> arr1 = { 1, 2, 3, 4, 5 };
    vector<int> arr2 = { 3, 7, 10, 15, 22 };
    vector<int> arr3 = { 4, 6, 8, 10 };
 
    // Find and print the smallest Fibonacci
    // product for each input array
    cout << "Output for arr1: "
         << findSmallestFibonacciProduct(arr1)
         << endl; // Output: 2
    cout << "Output for arr2: "
         << findSmallestFibonacciProduct(arr2)
         << endl; // Output: 21
    cout << "Output for arr3: "
         << findSmallestFibonacciProduct(arr3)
         << endl; // Output: -1
 
    return 0;
}


Java




import java.util.*;
 
public class GFG {
 
    // Function to check if a number
    // is a perfect square
    static boolean isPerfectSquare(int x) {
        int s = (int) Math.sqrt(x);
        return (s * s == x);
    }
 
    // Function to check if a number
    // is a Fibonacci number
    static boolean isFibonacci(int num) {
        return isPerfectSquare(5 * num * num + 4)
                || isPerfectSquare(5 * num * num - 4);
    }
 
    // Function to find the smallest Fibonacci
    // product from distinct pairs in an array
    static int findSmallestFibonacciProduct(ArrayList<Integer> arr) {
        int n = arr.size();
        int minFibProduct = Integer.MAX_VALUE;
 
        // Iterate through all pairs of distinct
        // numbers in the array
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                int product = arr.get(i) * arr.get(j);
 
                // Check if the product is a
                // Fibonacci number
                if (isFibonacci(product)) {
                    minFibProduct = Math.min(minFibProduct, product);
                }
            }
        }
 
        // If no Fibonacci product is found, return
        // -1; otherwise, return the smallest one
        if (minFibProduct == Integer.MAX_VALUE) {
            return -1;
        }
 
        return minFibProduct;
    }
 
    // Driver code
    public static void main(String[] args) {
 
        // Example input arrays
        ArrayList<Integer> arr1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
        ArrayList<Integer> arr2 = new ArrayList<>(Arrays.asList(3, 7, 10, 15, 22));
        ArrayList<Integer> arr3 = new ArrayList<>(Arrays.asList(4, 6, 8, 10));
 
        // Find and print the smallest Fibonacci
        // product for each input array
        System.out.println("Output for arr1: " + findSmallestFibonacciProduct(arr1)); // Output: 2
        System.out.println("Output for arr2: " + findSmallestFibonacciProduct(arr2)); // Output: 21
        System.out.println("Output for arr3: " + findSmallestFibonacciProduct(arr3)); // Output: -1
    }
}


Python3




import math
 
# Function to check if a number is a perfect square
def is_perfect_square(x):
    s = int(math.sqrt(x))
    return s * s == x
 
# Function to check if a number is a Fibonacci number
def is_fibonacci(num):
    return is_perfect_square(5 * num * num + 4) or is_perfect_square(5 * num * num - 4)
 
# Function to find the smallest Fibonacci product from distinct pairs in a list
def find_smallest_fibonacci_product(arr):
    n = len(arr)
    min_fib_product = float('inf')
 
    # Iterate through all pairs of distinct numbers in the list
    for i in range(n):
        for j in range(i + 1, n):
            product = arr[i] * arr[j]
 
            # Check if the product is a Fibonacci number
            if is_fibonacci(product):
                min_fib_product = min(min_fib_product, product)
 
    # If no Fibonacci product is found, return -1; otherwise, return the smallest one
    if min_fib_product == float('inf'):
        return -1
 
    return min_fib_product
 
# Driver code
def main():
    # Example input arrays
    arr1 = [1, 2, 3, 4, 5]
    arr2 = [3, 7, 10, 15, 22]
    arr3 = [4, 6, 8, 10]
 
    # Find and print the smallest Fibonacci product for each input array
    print("Output for arr1:", find_smallest_fibonacci_product(arr1)) 
    print("Output for arr2:", find_smallest_fibonacci_product(arr2)) 
    print("Output for arr3:", find_smallest_fibonacci_product(arr3)) 
 
if __name__ == "__main__":
    main()


C#




using System;
using System.Collections.Generic;
 
class Program
{
    // Function to check if a number is a perfect square
    static bool IsPerfectSquare(int x)
    {
        int s = (int)Math.Sqrt(x);
        return (s * s == x);
    }
 
    // Function to check if a number is a Fibonacci number
    static bool IsFibonacci(int num)
    {
        return IsPerfectSquare(5 * num * num + 4) || IsPerfectSquare(5 * num * num - 4);
    }
 
    // Function to find the smallest Fibonacci product from distinct pairs in an array
    static int FindSmallestFibonacciProduct(List<int> arr)
    {
        int n = arr.Count;
        int minFibProduct = int.MaxValue;
 
        // Iterate through all pairs of distinct numbers in the array
        for (int i = 0; i < n; i++)
        {
            for (int j = i + 1; j < n; j++)
            {
                int product = arr[i] * arr[j];
 
                // Check if the product is a Fibonacci number
                if (IsFibonacci(product))
                {
                    minFibProduct = Math.Min(minFibProduct, product);
                }
            }
        }
 
        // If no Fibonacci product is found, return -1; otherwise, return the smallest one
        if (minFibProduct == int.MaxValue)
        {
            return -1;
        }
 
        return minFibProduct;
    }
 
    // Driver code
    static void Main()
    {
        // Example input arrays
        List<int> arr1 = new List<int> { 1, 2, 3, 4, 5 };
        List<int> arr2 = new List<int> { 3, 7, 10, 15, 22 };
        List<int> arr3 = new List<int> { 4, 6, 8, 10 };
 
        // Find and print the smallest Fibonacci product for each input array
        Console.WriteLine("Output for arr1: " + FindSmallestFibonacciProduct(arr1)); // Output: 2
        Console.WriteLine("Output for arr2: " + FindSmallestFibonacciProduct(arr2)); // Output: 21
        Console.WriteLine("Output for arr3: " + FindSmallestFibonacciProduct(arr3)); // Output: -1
    }
}


Javascript




// Function to check if a number is a perfect square
function isPerfectSquare(x) {
    let s = Math.sqrt(x);
    return (s * s === x);
}
 
// Function to check if a number is a Fibonacci number
function isFibonacci(num) {
    return isPerfectSquare(5 * num * num + 4) || isPerfectSquare(5 * num * num - 4);
}
 
// Function to find the smallest Fibonacci product from distinct pairs in an array
function findSmallestFibonacciProduct(arr) {
    let n = arr.length;
    let minFibProduct = Infinity;
 
    // Iterate through all pairs of distinct numbers in the array
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {
            let product = arr[i] * arr[j];
 
            // Check if the product is a Fibonacci number
            if (isFibonacci(product)) {
                minFibProduct = Math.min(minFibProduct, product);
            }
        }
    }
 
    // If no Fibonacci product is found, return -1; otherwise, return the smallest one
    if (minFibProduct === Infinity) {
        return -1;
    }
 
    return minFibProduct;
}
 
// Example input arrays
let arr1 = [1, 2, 3, 4, 5];
let arr2 = [3, 7, 10, 15, 22];
let arr3 = [4, 6, 8, 10];
 
// Find and print the smallest Fibonacci product for each input array
console.log("Output for arr1:", findSmallestFibonacciProduct(arr1)); // Output: 2
console.log("Output for arr2:", findSmallestFibonacciProduct(arr2)); // Output: 21
console.log("Output for arr3:", findSmallestFibonacciProduct(arr3)); // Output: -1


Output

Output for arr1: 2
Output for arr2: 21
Output for arr3: -1








Time Complexity: O(n), Where n is the length of the array.
Auxiliary Space: O(1), As we are not using any extra space.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads