text: Sum of Fibonacci Numbers with alternate negatives | Computes value of first fibonacci numbers and stores their alternate sum ; Initialize result ; Add remaining terms ; For even terms ; For odd terms ; Return the alternating sum ; Get n ; Find the alternating sum
code: function calculateAlternateSum ( n ) { if ( n <= 0 ) return 0 ; var fibo = Array ( n + 1 ) . fill ( 0 ) ; fibo [ 0 ] = 0 ; fibo [ 1 ] = 1 ; var sum = Math . pow ( fibo [ 0 ] , 2 ) + Math . pow ( fibo [ 1 ] , 2 ) ; for ( i = 2 ; i <= n ; i ++ ) { fibo [ i ] = fibo [ i - 1 ] + fibo [ i - 2 ] ; if ( i % 2 == 0 ) sum -= fibo [ i ] ; else sum += fibo [ i ] ; } return sum ; } var n = 8 ; document . write ( " " + n + " " + calculateAlternateSum ( n ) ) ;