Distinct pairs from given arrays (a[i], b[j]) such that (a[i] + b[j]) is a Fibonacci number

Given two arrays a[] and b[], the task is to count the pairs (a[i], b[j]) such that (a[i] + b[j]) is a Fibonacci number.Note that (a, b) is equal to (b, a) and will be counted once.Â
First few Fibonacci numbers are:Â
Â
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141, …..
Examples:Â
Â
Input: a[] = {99, 1, 33, 2}, b[] = {1, 11, 2}Â
Output: 4Â
Total distinct pairs are (1, 1), (1, 2), (33, 1) and (2, 11)
Input: a[] = {5, 0, 8}, b[] = {0, 9}Â
Output: 3Â
Â
Â
Approach:Â
Â
- Take an empty set.
- Run two nested loops to generate all possible pairs from the two arrays taking one element from first array(call it a) and one from second array(call it b).
- Apply fibonacci test on (a + b) i.e. in order for a number x to be a Fibonacci number, any one of either 5 * x2 + 4 or 5 * x2 – 4 must be a perfect square.
- If it is Fibonacci number then push (a, b) in the set, if a < b or (b, a) if b < a. This is done to avoid duplicacy.
- The size of the set in the end is the total count of valid pairs.
Below is the implementation of the above approach:Â
Â
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;Â
// Function that returns true if// x is a perfect squarebool isPerfectSquare(long double x){    // Find floating point value of    // square root of x    long double sr = sqrt(x);Â
    // If square root is an integer    return ((sr - floor(sr)) == 0);}Â
// Function that returns true if// n is a Fibonacci Numberbool isFibonacci(int n){Â Â Â Â return isPerfectSquare(5 * n * n + 4)Â Â Â Â Â Â Â Â Â Â Â || isPerfectSquare(5 * n * n - 4);}Â
// Function to return the count of distinct pairs// from the given array such that the sum of the// pair elements is a Fibonacci numberint totalPairs(int a[], int b[], int n, int m){    // Set is used to avoid duplicate pairs    set<pair<int, int> > s;Â
    for (int i = 0; i < n; i++) {        for (int j = 0; j < m; j++) {Â
            // If sum is a Fibonacci number            if (isFibonacci(a[i] + b[j]) == true) {                if (a[i] < b[j])                    s.insert(make_pair(a[i], b[j]));                else                    s.insert(make_pair(b[j], a[i]));            }        }    }Â
    // Return the size of the set    return s.size();}Â
// Driver codeint main(){Â Â Â Â int a[] = { 99, 1, 33, 2 };Â Â Â Â int b[] = { 1, 11, 2 };Â Â Â Â int n = sizeof(a) / sizeof(a[0]);Â Â Â Â int m = sizeof(b) / sizeof(b[0]);Â
    cout << totalPairs(a, b, n, m);    return 0;} |
Java
// Java implementation of the approachimport java.util.*;Â
class GFG {Â Â Â Â Â static class pair{ Â Â Â Â int first, second; Â Â Â Â public pair(int first, int second) Â Â Â Â { Â Â Â Â Â Â Â Â this.first = first; Â Â Â Â Â Â Â Â this.second = second; Â Â Â Â } } Â
// Function that returns true if// x is a perfect squarestatic boolean isPerfectSquare(double x){    // Find floating point value of    // square root of x    double sr = Math.sqrt(x);Â
    // If square root is an integer    return ((sr - Math.floor(sr)) == 0);}Â
// Function that returns true if// n is a Fibonacci Numberstatic boolean isFibonacci(int n){Â Â Â Â return isPerfectSquare(5 * n * n + 4) || Â Â Â Â Â Â Â Â Â Â Â isPerfectSquare(5 * n * n - 4);}Â
// Function to return the count of distinct pairs// from the given array such that the sum of the// pair elements is a Fibonacci numberstatic int totalPairs(int a[], int b[],                       int n, int m){    // Set is used to avoid duplicate pairs    List<pair> s = new LinkedList<>();Â
    for (int i = 0; i < n; i++)     {        for (int j = 0; j < m; j++)         {Â
            // If sum is a Fibonacci number            if (isFibonacci(a[i] + b[j]) == true)             {                                 if (a[i] < b[j])                {                    if(checkDuplicate(s, new pair(a[i], b[j])))                        s.add(new pair(a[i], b[j]));                }                else                {                    if(checkDuplicate(s, new pair(b[j], a[i])))                        s.add(new pair(b[j], a[i]));                }            }        }    }Â
    // Return the size of the set    return s.size();}Â
static boolean checkDuplicate(List<pair> pairList, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â pair newPair){Â Â Â Â for(pair p: pairList)Â Â Â Â {Â Â Â Â Â Â Â Â if(p.first == newPair.first && Â Â Â Â Â Â Â Â Â Â Â p.second == newPair.second)Â Â Â Â Â Â Â Â Â Â Â Â return false;Â Â Â Â }Â Â Â Â return true;} Â
// Driver codepublic static void main(String[] args) {Â Â Â Â int a[] = { 99, 1, 33, 2 };Â Â Â Â int b[] = { 1, 11, 2 };Â Â Â Â int n = a.length;Â Â Â Â int m = b.length;Â
    System.out.println(totalPairs(a, b, n, m));}} Â
// This code is contributed by Rajput-Ji |
Python3
# Python3 implementation of the approach from math import sqrt,floorÂ
# Function that returns true if # x is a perfect square def isPerfectSquare(x) : Â
    # Find floating point value of     # square root of x     sr = sqrt(x)Â
    # If square root is an integer     return ((sr - floor(sr)) == 0)Â
# Function that returns true if # n is a Fibonacci Number def isFibonacci(n ) : Â
    return (isPerfectSquare(5 * n * n + 4) or            isPerfectSquare(5 * n * n - 4))Â
# Function to return the count of distinct pairs # from the given array such that the sum of the # pair elements is a Fibonacci number def totalPairs(a, b, n, m) :Â
    # Set is used to avoid duplicate pairs     s = set(); Â
    for i in range(n) :        for j in range(m) :Â
            # If sum is a Fibonacci number             if (isFibonacci(a[i] + b[j]) == True) :                if (a[i] < b[j]) :                    s.add((a[i], b[j]));                 else :                    s.add((b[j], a[i])); Â
    # Return the size of the set     return len(s); Â
# Driver code if __name__ == "__main__" : Â Â Â Â Â Â Â Â Â a = [ 99, 1, 33, 2 ]; Â Â Â Â b = [ 1, 11, 2 ];Â Â Â Â n = len(a);Â Â Â Â m = len(b); Â
    print(totalPairs(a, b, n, m)); Â
# This code is contributed by Ryuga |
C#
// C# implementation of the approachusing System;using System.Collections.Generic;Â Â Â Â Â Â Â Â Â Â Â Â Â
class GFG {public class pair{ Â Â Â Â public int first, second; Â Â Â Â public pair(int first, int second) Â Â Â Â { Â Â Â Â Â Â Â Â this.first = first; Â Â Â Â Â Â Â Â this.second = second; Â Â Â Â } } Â
// Function that returns true if// x is a perfect squarestatic bool isPerfectSquare(double x){    // Find floating point value of    // square root of x    double sr = Math.Sqrt(x);Â
    // If square root is an integer    return ((sr - Math.Floor(sr)) == 0);}Â
// Function that returns true if// n is a Fibonacci Numberstatic bool isFibonacci(int n){Â Â Â Â return isPerfectSquare(5 * n * n + 4) || Â Â Â Â Â Â Â Â Â Â Â isPerfectSquare(5 * n * n - 4);}Â
// Function to return the count of distinct pairs// from the given array such that the sum of the// pair elements is a Fibonacci numberstatic int totalPairs(int []a, int []b,                       int n, int m){    // Set is used to avoid duplicate pairs    List<pair> s = new List<pair>();Â
    for (int i = 0; i < n; i++)     {        for (int j = 0; j < m; j++)         {Â
            // If sum is a Fibonacci number            if (isFibonacci(a[i] + b[j]) == true)             {                                 if (a[i] < b[j])                {                    if(checkDuplicate(s, new pair(a[i], b[j])))                                   s.Add(new pair(a[i], b[j]));                }                else                {                    if(checkDuplicate(s, new pair(b[j], a[i])))                                   s.Add(new pair(b[j], a[i]));                }            }        }    }Â
    // Return the size of the set    return s.Count;}Â
static bool checkDuplicate(List<pair> pairList, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â pair newPair){Â Â Â Â foreach(pair p in pairList)Â Â Â Â {Â Â Â Â Â Â Â Â if(p.first == newPair.first && Â Â Â Â Â Â Â Â Â Â Â p.second == newPair.second)Â Â Â Â Â Â Â Â Â Â Â Â return false;Â Â Â Â }Â Â Â Â return true;} Â
// Driver codepublic static void Main(String[] args) {Â Â Â Â int []a = { 99, 1, 33, 2 };Â Â Â Â int []b = { 1, 11, 2 };Â Â Â Â int n = a.Length;Â Â Â Â int m = b.Length;Â
    Console.WriteLine(totalPairs(a, b, n, m));}} Â
// This code is contributed by Rajput-Ji |
Javascript
<script>Â
// Javascript implementation of the approachÂ
// Function that returns true if// x is a perfect squarefunction isPerfectSquare(x){    // Find floating point value of    // square root of x    var sr = Math.sqrt(x);Â
    // If square root is an integer    return ((sr - Math.floor(sr)) == 0);}Â
// Function that returns true if// n is a Fibonacci Numberfunction isFibonacci(n){Â Â Â Â return isPerfectSquare(5 * n * n + 4)Â Â Â Â Â Â Â Â Â Â Â || isPerfectSquare(5 * n * n - 4);}Â
// Function to return the count of distinct pairs// from the given array such that the sum of the// pair elements is a Fibonacci numberfunction totalPairs(a, b, n, m){    // Set is used to avoid duplicate pairs    var s = new Set();Â
    for (var i = 0; i < n; i++) {        for (var j = 0; j < m; j++) {Â
            // If sum is a Fibonacci number            if (isFibonacci(a[i] + b[j])) {                if (a[i] < b[j])                {                    var tmp = a[i]+" "+b[j];                    s.add(tmp);                }                else                {                    var tmp = b[j]+" "+a[i];                    s.add(tmp);                }            }        }    }Â
    // Return the size of the set    return s.size;}Â
// Driver codevar a = [99, 1, 33, 2 ];var b = [1, 11, 2 ];var n = a.length;var m = b.length;document.write( totalPairs(a, b, n, m));Â
</script> |
Output:Â
4
Â
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



