Check whether Array represents a Fibonacci Series or not
Last Updated :
26 Apr, 2023
Given an array arr[] consisting of N integers, the task is to check whether a Fibonacci series can be formed using all the array elements or not. If possible, print "Yes". Otherwise, print "No".
Examples:
Input: arr[] = { 8, 3, 5, 13 }
Output: Yes
Explanation:
Rearrange given array as {3, 5, 8, 13} and these numbers form Fibonacci series.
Input: arr[] = { 2, 3, 5, 11 }
Output: No
Explanation:
The given array elements do not form a Fibonacci series.
Approach:
In order to solve the problem mentioned above, the main idea is to sort the given array. After sorting, check if every element is equal to the sum of the previous 2 elements. If so, then the array elements form a Fibonacci series.
Algorithm:
- Define a function named checkIsFibonacci that takes an array of integers and its size as input.
- Check if the size of the array is 1 or 2. If yes, return true as an array of 1 or 2 elements can always form a Fibonacci series.
- Sort the array in ascending order using the sort() function from the algorithm header.
- Traverse the sorted array from index 2 to n-1.
- Check if the current element is equal to the sum of the previous two elements of the array. If not, return false.
- If all the elements pass the above condition, return true.
- In the main function:
a. Define an array of integers and its size.
b. Call the checkIsFibonacci() function with the array and its size as arguments.
c. If the function returns true, print "Yes" to the console. Otherwise, print "No".
8. End of the program.
Below is the implementation of the above approach:
C++
// C++ program to check if the
// elements of a given array
// can form a Fibonacci Series
#include <bits/stdc++.h>
using namespace std;
// Returns true if a permutation
// of arr[0..n-1] can form a
// Fibonacci Series
bool checkIsFibonacci(int arr[], int n)
{
if (n == 1 || n == 2)
return true;
// Sort array
sort(arr, arr + n);
// After sorting, check if every
// element is equal to the
// sum of previous 2 elements
for (int i = 2; i < n; i++)
if ((arr[i - 1] + arr[i - 2])
!= arr[i])
return false;
return true;
}
// Driver Code
int main()
{
int arr[] = { 8, 3, 5, 13 };
int n = sizeof(arr) / sizeof(arr[0]);
if (checkIsFibonacci(arr, n))
cout << "Yes" << endl;
else
cout << "No";
return 0;
}
Java
// Java program to check if the elements of
// a given array can form a Fibonacci Series
import java. util. Arrays;
class GFG{
// Returns true if a permutation
// of arr[0..n-1] can form a
// Fibonacci Series
public static boolean checkIsFibonacci(int arr[],
int n)
{
if (n == 1 || n == 2)
return true;
// Sort array
Arrays.sort(arr);
// After sorting, check if every
// element is equal to the sum
// of previous 2 elements
for(int i = 2; i < n; i++)
{
if ((arr[i - 1] + arr[i - 2]) != arr[i])
return false;
}
return true;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 8, 3, 5, 13 };
int n = arr.length;
if (checkIsFibonacci(arr, n))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by divyeshrabadiya07
Python3
# Python3 program to check if the
# elements of a given array
# can form a Fibonacci Series
# Returns true if a permutation
# of arr[0..n-1] can form a
# Fibonacci Series
def checkIsFibonacci(arr, n) :
if (n == 1 or n == 2) :
return True;
# Sort array
arr.sort()
# After sorting, check if every
# element is equal to the
# sum of previous 2 elements
for i in range(2, n) :
if ((arr[i - 1] +
arr[i - 2])!= arr[i]) :
return False;
return True;
# Driver Code
if __name__ == "__main__" :
arr = [ 8, 3, 5, 13 ];
n = len(arr);
if (checkIsFibonacci(arr, n)) :
print("Yes");
else :
print("No");
# This code is contributed by AnkitRai01
C#
// C# program to check if the elements of
// a given array can form a fibonacci series
using System;
class GFG{
// Returns true if a permutation
// of arr[0..n-1] can form a
// fibonacci series
public static bool checkIsFibonacci(int []arr,
int n)
{
if (n == 1 || n == 2)
return true;
// Sort array
Array.Sort(arr);
// After sorting, check if every
// element is equal to the sum
// of previous 2 elements
for(int i = 2; i < n; i++)
{
if ((arr[i - 1] + arr[i - 2]) != arr[i])
return false;
}
return true;
}
// Driver code
public static void Main(string[] args)
{
int []arr = { 8, 3, 5, 13 };
int n = arr.Length;
if (checkIsFibonacci(arr, n))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by AnkitRai01
JavaScript
<script>
// Javascript program to check if the elements of
// a given array can form a Fibonacci Series
// Returns true if a permutation
// of arr[0..n-1] can form a
// Fibonacci Series
function checkIsFibonacci(arr , n)
{
if (n == 1 || n == 2)
return true;
// Sort array
arr.sort((a, b) => a - b);
// After sorting, check if every
// element is equal to the sum
// of previous 2 elements
for (i = 2; i < n; i++) {
if ((arr[i - 1] + arr[i - 2]) != arr[i])
return false;
}
return true;
}
// Driver code
var arr = [ 8, 3, 5, 13 ];
var n = arr.length;
if (checkIsFibonacci(arr, n))
document.write("Yes");
else
document.write("No");
// This code contributed by umadevi9616
</script>
Time Complexity: O(N Log N)
Auxiliary Space: O(1)
Approach 2: Using Stacks;
Here's how the stack checks if an array can form a Fibonacci series:
We start by pushing the first two elements of the array onto the stack.
Then, for each subsequent element in the array, we check if it is equal to the sum of the two elements on top of the stack.
If it is, we push the element onto the stack.
If it isn't, we return false, indicating that the array cannot form a Fibonacci series.
If we reach the end of the array without returning false, we return true, indicating that the array can form a Fibonacci series.
C++
#include <iostream>
#include <stack>
#include <algorithm>
using namespace std;
bool checkIsFibonacci(int arr[], int n) {
if (n == 1 || n == 2) {
return true;
}
// Sort array
sort(arr, arr+n);
// Use stack to check if every element is equal to the sum of previous 2 elements
stack<int> s;
for (int i = 0; i < n; i++) {
if (i < 2) {
s.push(arr[i]);
} else {
if (s.top() + s.size() - 2 == arr[i]) {
s.push(arr[i]);
} else {
return false;
}
}
}
return true;
}
int main() {
int arr[] = {8, 3, 5, 13};
int n = sizeof(arr)/sizeof(arr[0]);
if (checkIsFibonacci(arr, n)) {
cout << "No" << endl;
} else {
cout << "Yes" << endl;
}
return 0;
}
Java
import java.util.*;
public class CheckFibonacci {
public static void main(String[] args) {
int[] arr = {8, 3, 5, 13};
int n = arr.length;
if (checkIsFibonacci(arr, n)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
public static boolean checkIsFibonacci(int[] arr, int n) {
if (n == 1 || n == 2) {
return true;
}
// Sort array
Arrays.sort(arr);
// Use stack to check if every element is equal to the sum of previous 2 elements
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < n; i++) {
if (i < 2) {
stack.push(arr[i]);
} else {
if (stack.peek() + stack.get(stack.size() - 2) == arr[i]) {
stack.push(arr[i]);
} else {
return false;
}
}
}
return true;
}
}
Python3
# Python3 program to check if the
# elements of a given array
# can form a Fibonacci Series
# using stack
# Returns true if a permutation
# of arr[0..n-1] can form a
# Fibonacci Series
def checkIsFibonacci(arr, n) :
if (n == 1 or n == 2) :
return True;
# Sort array
arr.sort()
# Use stack to check if every
# element is equal to the
# sum of previous 2 elements
stack = []
for i in range(n):
if i < 2:
stack.append(arr[i])
else:
if stack[-1] + stack[-2] == arr[i]:
stack.append(arr[i])
else:
return False
return True;
# Driver Code
if __name__ == "__main__" :
arr = [ 8, 3, 5, 13 ]
n = len(arr)
if (checkIsFibonacci(arr, n)) :
print("Yes")
else :
print("No")
C#
// C# code addition
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
// Function to check whether the given array number are fibonnaci
static bool CheckIsFibonacci(int[] arr, int n) {
if (n == 1 || n == 2) {
return true;
}
// Sort array
Array.Sort(arr);
// Use stack to check if every element is equal to the sum of previous 2 elements
Stack<int> s = new Stack<int>();
for (int i = 0; i < n; i++) {
if (i < 2) {
s.Push(arr[i]);
} else {
if (s.Peek() + s.ElementAt(s.Count - 2) == arr[i]) {
s.Push(arr[i]);
} else {
return false;
}
}
}
return true;
}
// Driver code.
static void Main(string[] args) {
int[] arr = {8, 3, 5, 13};
int n = arr.Length;
if (CheckIsFibonacci(arr, n)) {
Console.WriteLine("No");
} else {
Console.WriteLine("Yes");
}
}
}
// The code is contributed by Arushi Goel.
JavaScript
// Javascript program to check if the
// elements of a given array
// can form a Fibonacci Series
// using stack
// Returns true if a permutation
// of arr[0..n-1] can form a
// Fibonacci Series
function checkIsFibonacci(arr, n) {
if (n == 1 || n == 2) {
return true;
}
// Sort array
arr.sort((a, b) => a - b);
// Use stack to check if every
// element is equal to the
// sum of previous 2 elements
let stack = [];
for (let i = 0; i < n; i++) {
if (i < 2) {
stack.push(arr[i]);
} else {
if (stack[stack.length - 1] + stack[stack.length - 2] == arr[i]) {
stack.push(arr[i]);
} else {
return false;
}
}
}
return true;
}
// Driver Code
let arr = [8, 3, 5, 13];
let n = arr.length;
if (checkIsFibonacci(arr, n)) {
console.log("Yes");
} else {
console.log("No");
}
// Contributed by adityasha4x71
Time Complexity: O(N Log N)
Auxiliary Space: O(N)
Similar Reads
Check whether the given array is perfect or not
There is an array containing some non-negative integers. Check whether the array is perfect or not. An array is called perfect if it is first strictly increasing, then constant and finally strictly decreasing. Any of the three parts can be empty. Examples: Input : arr[] = {1, 8, 8, 8, 3, 2}Output :
5 min read
Check if an array represents Inorder of Binary Search tree or not
Given an array of n elements. The task is to check if it is an Inorder traversal of any Binary Search Tree or not.Examples: Input: arr[] = { 19, 23, 25, 30, 45 }Output: trueExplanation: As the array is sorted in non-decreasing order, it is an Inorder traversal of any Binary Search Tree. Input : arr[
4 min read
Check in binary array the number represented by a subarray is odd or even
Given an array such that all its terms is either 0 or 1.You need to tell the number represented by a subarray a[l..r] is odd or even Examples : Input : arr = {1, 1, 0, 1} l = 1, r = 3 Output : odd number represented by arr[l...r] is 101 which 5 in decimal form which is odd Input : arr = {1, 1, 1, 1}
4 min read
Nth term of a Custom Fibonacci series
Given three integers A, B and N. A Custom Fibonacci series is defined as F(x) = F(x - 1) + F(x + 1) where F(1) = A and F(2) = B. Now the task is to find the Nth term of this series.Examples: Input: A = 10, B = 17, N = 3 Output: 7 10, 17, 7, -10, -17, ...Input: A = 50, B = 12, N = 10 Output: -50 Appr
4 min read
Check whether the given String is good for any ascending Array or not
Given a string S of length N. Consider any ascending array A[] such that each A[i] > 0 for all (1 <= i <= N) and some conditions, the task is to output YES/NO, by checking that the above-given conditions are true for all possible ascending A[]'s or not with given S. Sum up all the elements
7 min read
Remove all the fibonacci numbers from the given array
Given an array arr[] of N integers, the task is to remove all the fibonacci numbers present in the array.Examples: Input: arr[] = {4, 6, 5, 3, 8, 7, 10, 11, 14, 15} Output: 4 6 7 10 11 14 15 Explanation: The array contains 3 fibonacci data values 5, 3 and 8. These values have been removed from the a
9 min read
Find two Fibonacci numbers whose sum can be represented as N
Given an even number N, the task is to find two Fibonacci numbers whose sum can be represented as N. There may be several combinations possible. Print only first such pair. If there is no solution then print -1.Examples: Input: N = 90 Output: 1, 89 Explanation: The first pair with whose sum is equal
6 min read
Check whether the frequency of the elements in the Array is unique or not
Given an array arr[] of N integers, the task is to check whether the frequency of the elements in the array is unique or not, or in other words, there are no two distinct numbers in an array with equal frequency. If all the frequency is unique then Print "YES", else Print "NO". Examples: Input: N =
5 min read
Program to check if an Array is Palindrome or not
Given an array, the task is to determine whether an array is a palindrome or not.Examples: Input: arr[] = {3, 6, 0, 6, 3} Output: Palindrome Input: arr[] = {1, 2, 3, 4, 5} Output: Not Palindrome Approach: Initialise flag to unset int flag = 0.Loop the array till size n/2In a loop check if arr[i]! =
5 min read
Check if all array elements are present in a given stack or not
Given a stack of integers S and an array of integers arr[], the task is to check if all the array elements are present in the stack or not. Examples: Input: S = {10, 20, 30, 40, 50}, arr[] = {20, 30}Output: YesExplanation:Elements 20 and 30 are present in the stack. Input: S = {50, 60}, arr[] = {60,
5 min read