Even Fibonacci Numbers Sum | Find the sum of all the even - valued terms in the Fibonacci sequence which do not exceed given limit . ; Returns sum of even Fibonacci numbers which are less than or equal to given limit . ; Initialize first two even prime numbers and their sum ; calculating sum of even Fibonacci value ; get next even value of Fibonacci sequence ; If we go beyond limit , we break loop ; Move to next even number and update sum ; Driver code
import java . io . * ; class GFG { static int evenFibSum ( int limit ) { if ( limit < 2 ) return 0 ; long ef1 = 0 , ef2 = 2 ; long sum = ef1 + ef2 ; while ( ef2 <= limit ) { long ef3 = 4 * ef2 + ef1 ; if ( ef3 > limit ) break ; ef1 = ef2 ; ef2 = ef3 ; sum += ef2 ; } return ( int ) sum ; } public static void main ( String [ ] args ) { int limit = 400 ; System . out . println ( evenFibSum ( limit ) ) ; } }