w3resource

C++ Exercises: Display first 10 Fermat numbers


33. Display First 10 Fermat Numbers

Write a C++ program to display the first 10 Fermat numbers.

Sample Solution:

C++ Code :

# include <iostream> // Including input-output stream library
# include <math.h> // Including math library for mathematical functions
using namespace std; // Using the standard namespace

int main() // Start of the main function
{
    int n = 0; // Initializing variable n to 0
    double result; // Declare a variable to store the result (a Fermat number)

    cout << "\n\n Display first 10 Fermat numbers:\n"; // Display purpose
    cout << "-------------------------------------\n"; // Display purpose
    cout << " The first 10 Fermat numbers are: "<<endl; // Display purpose

    while (n <= 10) // Loop to generate the first 10 Fermat numbers
    {
        result = pow(2, pow(2, n)) + 1; // Calculate the nth Fermat number
        n++; // Increment n for the next iteration
        cout << result << endl; // Output the Fermat number
    }
}

Sample Output:

 Display first 10 Fermat numbers:                                      
-------------------------------------                                  
 The first 10 Fermat numbers are:                                      
3                                                                      
5                                                                      
17                                                                     
257                                                                    
65537                                                                  
4.29497e+09                                                            
1.84467e+19                                                            
3.40282e+38                                                            
1.15792e+77                                                            
1.34078e+154                                                           
inf      

Flowchart:

Flowchart: Display first 10 Fermat numbers

For more Practice: Solve these Related Problems:

  • Write a C++ program to generate the first 10 Fermat numbers using power functions and long double arithmetic.
  • Write a C++ program to compute Fermat numbers iteratively with checks for potential overflow.
  • Write a C++ program to display Fermat numbers with scientific notation formatting for large values.
  • Write a C++ program to calculate and print the first 10 Fermat numbers using recursion for exponentiation.

Go to:


PREV : Perfect Cube Check.
NEXT : Express Number as Sum of Two Cubes in Two Ways.

C++ Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.