w3resource

C++ Exercises: Display first 10 Fermat numbers

C++ Numbers: Exercise-33 with Solution

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

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a program in C++ to check whether a given number is a perfect cube or not.
Next: Write a program in C++ to find any number between 1 and n that can be expressed as the sum of two cubes in two (or more) different ways.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/cpp-exercises/numbers/cpp-numbers-exercise-33.php