Count pairs with Fibonacci sum from two arrays

Updated

Given two arrays with unequal sizes, you have to take one element from first array(say a) and one element from array 2(say b). If the sum of a and b is a fibonacci number, that (a,b) makes a valid pair. You have to count number of such pairs. Note : (a,b) is equal to (b,a) First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ..

Examples :

Input : arr1[] = {99, 1, 33, 2}, arr2[] = {1, 11, 2}
Output : 4
Explanation :
Total distinct pairs are: (1, 1), (1, 2), (33, 1), (2, 11)

Input : arr1[] = {5, 0, 8}, arr2[] = {0, 9}
Output : 3

Approach :

  1. Take one empty sets s1.
  2. 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).
  3. Apply fibonacci test, on (a+b), to check if the sum is a fibonacci number. Fibonacci test is as follows: A number is Fibonacci if and only if one or both of (5*n^2 + 4) or (5*n^2 – 4) is a perfect square
  4. If it is fibonacci number, then push (a,b) pair in s1, if a is less than b, or (b,a) if b is less than a. This is done to avoid duplicacy.
  5. The size of the set is the total pairs.
// C++ program to count total 
// number of pairs 
	
#include <bits/stdc++.h> 
using namespace std; 

// A utility function that returns true if x is perfect square 
bool isPerfectSquare(int x) 
{ 
	int s = sqrt(x); 
	return (s*s == x); 
} 

// Returns true if n is a Fibinnaci Number, else false 
bool isFibonacci(int n) 
{ 
	// n is Fibinacci if one of 5*n*n + 4 or 5*n*n - 4 or both 
	// is a perferct square 
	return isPerfectSquare(5*n*n + 4) || 
		isPerfectSquare(5*n*n - 4); 
} 

// Function to return the total pairs 
// of elements such that sum of both element is a fibonacci number
int totalPairs(int arr1[], int arr2[], int n, int m) 
{ 
	// set is used to avoid duplicate pairs 
	set <pair<int, int> > s1;
	int a,b;
	
	for (int i = 0; i < n; i++) { 
					
				for (int j = 0; j < m; j++) { 
				
				a = arr1[i];
				b = arr2[j];
				
				if (isFibonacci(a + b) == true)
				{
				if (a < b)
					s1.insert(make_pair(a,b));
				else
					s1.insert(make_pair(b,a));
				}
			} 
	} 
	
	// return size of the set s1 
	return s1.size(); 
} 
	
// Driver code 
int main() 
{ 

	int arr1[] = {2, 7, 1}; 
	int arr2[] = { 5, 1, 10, 6 }; 
	int n = sizeof(arr1) / sizeof(arr1[0]); 
	int m = sizeof(arr2) / sizeof(arr2[0]); 
	
	cout << totalPairs(arr1, arr2, n, m); 
	return 0; 
} 

Output :

5
Comment
Next tutorial
Mithlesh Upadhyay Published 3 Nov 2026 · 3 min read

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.

Related tutorials