Find length of longest Fibonacci like subsequence | Function to return the max Length of Fibonacci subsequence ; Store all array elements in a hash table ; check until next fib element is found ; next element of fib subseq ; Driver program
function LongestFibSubseq ( A , n ) { var S = new Set ( A ) ; var maxLen = 0 , x , y ; for ( var i = 0 ; i < n ; ++ i ) { for ( var j = i + 1 ; j < n ; ++ j ) { x = A [ j ] ; y = A [ i ] + A [ j ] ; var length = 2 ; while ( S . has ( y ) ) { var z = x + y ; x = y ; y = z ; maxLen = Math . max ( maxLen , ++ length ) ; } } } return maxLen >= 3 ? maxLen : 0 ; } var A = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ] ; var n = A . length ; document . write ( LongestFibSubseq ( A , n ) ) ;