﻿ C++ Exercises: Display first 10 Fermat numbers - w3resource

# C++ Exercises: Display first 10 Fermat numbers

## C++ Numbers: Exercise-33 with Solution

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

Sample Solution:

C++ Code :

``````# include <iostream>
# include <math.h>
using namespace std;
int main()
{
int n=0;
double result;
cout << "\n\n Display first 10 Fermat numbers:\n";
cout << "-------------------------------------\n";
cout << " The first 10 Fermat numbers are: "<<endl;
while (n <= 10)
{
result= pow(2, pow(2, n)) + 1;
n++;
cout << result << endl;
}
}
``````

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:

C++ Code Editor:

What is the difficulty level of this exercise?

﻿

## C++ Programming: Tips of the Day

How to use the PI constant in C++?

On some (especially older) platforms (see the comments below) you might need to

#define _USE_MATH_DEFINES and then include the necessary header file:
`#include<math.h>`

and the value of pi can be accessed via:

`M_PI`

In math.h (2014) it is defined as:

`# define M_PI           3.14159265358979323846  /* pi */`

but check your math.h for more. An extract from the "old" math.h (in 2009):

```/* Define _USE_MATH_DEFINES before including math.h to expose these macro
* definitions for common math constants.  These are placed under an #ifdef
* since these commonly-defined names are not part of the C/C++ standards.
*/```

However:

1. on newer platforms (at least on my 64 bit Ubuntu 14.04) I do not need to define the _USE_MATH_DEFINES
2. On (recent) Linux platforms there are long double values too provided as a GNU Extension:
`# define M_PIl          3.14159265358979323846`

Ref: https://bit.ly/3G4BgzQ