Program to find first N Fermat Numbers | Iterative Function to calculate ( x ^ y ) in O ( log y ) ; 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
def power ( x , y ) : NEW_LINE INDENT while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = res * x NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT def Fermat ( i ) : NEW_LINE INDENT power2_i = power ( 2 , i ) NEW_LINE power2_2_i = power ( 2 , power2_i ) NEW_LINE return power2_2_i + 1 NEW_LINE DEDENT def Fermat_Number ( n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( Fermat ( i ) , end = " " ) NEW_LINE if ( i != n - 1 ) : NEW_LINE INDENT print ( end = " , ▁ " ) NEW_LINE DEDENT DEDENT DEDENT n = 7 NEW_LINE Fermat_Number ( n ) NEW_LINE