Program to find first N Fermat Numbers | Iterative Function to calculate ( x ^ y ) in O ( log y ) ; let res = 1 ; Initialize result ; If y is odd , multiply x with the result ; n must be even now y = y >> 1 ; y = y / 2 x = x * x ; Change x to x ^ 2 ; Function to find nth fermat number ; 2 to the power i ; 2 to the power 2 ^ i ; Function to find first n Fermat numbers ; Calculate 2 ^ 2 ^ i ; Driver code ; Function call
function power ( x , y ) { while ( y > 0 ) { if ( y & 1 ) res = res * x ; } return res ; } function Fermat ( i ) { let power2_i = power ( 2 , i ) ; let power2_2_i = power ( 2 , power2_i ) ; return power2_2_i + 1 ; } function Fermat_Number ( n ) { for ( let i = 0 ; i < n ; i ++ ) { document . write ( Fermat ( i ) ) ; if ( i != n - 1 ) document . write ( " " ) ; } } let n = 7 ; Fermat_Number ( n ) ;