Check whether Array represents a Fibonacci Series or not | C ++ 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 ; Sort array ; After sorting , check if every element is equal to the sum of previous 2 elements ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkIsFibonacci ( int arr [ ] , int n ) { if ( n == 1 n == 2 ) return true ; sort ( arr , arr + n ) ; for ( int i = 2 ; i < n ; i ++ ) if ( ( arr [ i - 1 ] + arr [ i - 2 ] ) != arr [ i ] ) return false ; return true ; } 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 ; }