Almkvist-Giullera formula for pi: Difference between revisions

Added C++ solution
m (changed to stitch operator for column display)
(Added C++ solution)
Line 162:
53 iterations required for 70 digits after the decimal point.
 
3.1415926535897932384626433832795028841971693993751058209749445923078164
</pre>
 
=={{header|C++}}==
{{libheader|Boost}}
{{libheader|GMP}}
<lang cpp>#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/multiprecision/gmp.hpp>
#include <iomanip>
#include <iostream>
 
namespace mp = boost::multiprecision;
using big_int = mp::mpz_int;
using big_float = mp::cpp_dec_float_100;
using rational = mp::mpq_rational;
 
big_int factorial(int n) {
big_int result = 1;
for (int i = 2; i <= n; ++i)
result *= i;
return result;
}
 
// Return the integer portion of the nth term of Almkvist-Giullera sequence.
big_int almkvist_giullera(int n) {
return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) /
(pow(factorial(n), 6) * 3);
}
 
int main() {
std::cout << "n | Integer portion of nth term\n"
<< "------------------------------------------------\n";
for (int n = 0; n < 10; ++n)
std::cout << n << " | " << std::setw(44) << almkvist_giullera(n)
<< '\n';
 
rational sum = 0, prev = 0;
rational prec(1, pow(big_int(10), 70));
for (int n = 0;; ++n) {
rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3));
sum += term;
if (abs(sum - prev) < prec)
break;
prev = sum;
}
big_float pi2(1 / sum);
std::cout << "\nPi to 70 decimal places is:\n";
std::cout << std::fixed << std::setprecision(70) << sqrt(pi2) << '\n';
}</lang>
 
{{out}}
<pre>
n | Integer portion of nth term
------------------------------------------------
0 | 96
1 | 5122560
2 | 190722470400
3 | 7574824857600000
4 | 312546150372456000000
5 | 13207874703225491420651520
6 | 567273919793089083292259942400
7 | 24650600248172987140112763715584000
8 | 1080657854354639453670407474439566400000
9 | 47701779391594966287470570490839978880000000
 
Pi to 70 decimal places is:
3.1415926535897932384626433832795028841971693993751058209749445923078164
</pre>
1,777

edits