Program to find first N Fermat Numbers | CPP program to print fermat numbers ; Iterative Function to calculate ( x ^ y ) in O ( log y ) ; llu 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
#include <bits/stdc++.h> NEW_LINE #include <boost/multiprecision/cpp_int.hpp> NEW_LINE using namespace boost :: multiprecision ; #define llu  int128_t NEW_LINE using namespace std ; llu power ( llu x , llu y ) { while ( y > 0 ) { if ( y & 1 ) res = res * x ; } return res ; } llu Fermat ( llu i ) { llu power2_i = power ( 2 , i ) ; llu power2_2_i = power ( 2 , power2_i ) ; return power2_2_i + 1 ; } void Fermat_Number ( llu n ) { for ( llu i = 0 ; i < n ; i ++ ) { cout << Fermat ( i ) ; if ( i != n - 1 ) cout << " , ▁ " ; } } int main ( ) { llu n = 7 ; Fermat_Number ( n ) ; return 0 ; }