Length of longest Fibonacci subarray | C ++ program for the above approach ; A utility function that returns true if x is perfect square ; Returns true if n is a Fibinacci Number , else false ; Here n is Fibinac ci if one of 5 * n * n + 4 or 5 * n * n - 4 or both is a perferct square ; Function to find the length of the largest sub - array of an array every element of whose is a Fibonacci number ; Traverse the array arr [ ] ; Check if arr [ i ] is a Fibonacci number ; Stores the maximum length of the Fibonacci number subarray ; Finally , return the maximum length ; Driver code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPerfectSquare ( int x ) { int s = sqrt ( x ) ; return ( s * s == x ) ; } bool isFibonacci ( int n ) { return isPerfectSquare ( 5 * n * n + 4 ) || isPerfectSquare ( 5 * n * n - 4 ) ; } int contiguousFibonacciNumber ( int arr [ ] , int n ) { int current_length = 0 ; int max_length = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( isFibonacci ( arr [ i ] ) ) { current_length ++ ; } else { current_length = 0 ; } max_length = max ( max_length , current_length ) ; } return max_length ; } int main ( ) { int arr [ ] = { 11 , 8 , 21 , 5 , 3 , 28 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << contiguousFibonacciNumber ( arr , n ) ; return 0 ; }