![]() |
VOOZH | about |
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:
Below is the implementation of the above approach:
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.