Check if sum of Fibonacci elements in an Array is a Fibonacci number or not | Java program to check whether the sum of fibonacci elements of the array is a Fibonacci number or not ; Hash to store the Fibonacci numbers up to Max ; Function to create the hash table to check Fibonacci numbers ; Inserting the first two Fibonacci numbers into the hash ; Add the remaining Fibonacci numbers based on the previous two numbers ; Function to check if the sum of Fibonacci numbers is Fibonacci or not ; Find the sum of all Fibonacci numbers ; Iterating through the array ; If the sum is Fibonacci then return true ; Driver code ; array of elements ; Creating a set containing all fibonacci numbers
import java . util . * ; class GFG { static final int MAX = 100005 ; static HashSet < Integer > fibonacci = new HashSet < Integer > ( ) ; static void createHash ( ) { int prev = 0 , curr = 1 ; fibonacci . add ( prev ) ; fibonacci . add ( curr ) ; while ( curr <= MAX ) { int temp = curr + prev ; fibonacci . add ( temp ) ; prev = curr ; curr = temp ; } } static boolean checkArray ( int arr [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( fibonacci . contains ( arr [ i ] ) ) sum += arr [ i ] ; if ( fibonacci . contains ( sum ) ) return true ; return false ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 4 , 8 , 2 } ; int n = arr . length ; createHash ( ) ; if ( checkArray ( arr , n ) ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } }