Search code examples
c++for-looppi

How to get my pi generating code to cut off at 300?


I am trying to write a program that allows for pi to be gernated to the 300th digit, but I cannot seem to figure out how to cut it off at the 300th digit.

As of right now the code was ran forever and any other method I have tried has not worked like cutting off at a specfiec time, however this is not what I need to happen.

#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>

using namespace boost::multiprecision;

class Gospers
{
    cpp_int q, r, t, i, n;

public:    

    // use Gibbons spigot algorith based on the Gospers series
    Gospers() : q{1}, r{0}, t{1}, i{1}
    {
        ++*this; // move to the first digit
    }

    // the ++ prefix operator will move to the next digit
    Gospers& operator++()
    {
        n = (q*(27*i-12)+5*r) / (5*t);

        while(n != (q*(675*i-216)+125*r)/(125*t))
        {
            r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r);
            q = i*(2*i-1)*q;
            t = 3*(3*i+1)*(3*i+2)*t;
            i++;

            n = (q*(27*i-12)+5*r) / (5*t);
        }

        q = 10*q;
        r = 10*r-10*n*t;

        return *this;
    }

    // the dereference operator will give the current digit
    int operator*()
    {
        return (int)n;
    }
};

int main()
{
    Gospers g;

    std::cout << *g << ".";  // print the first digit and the decimal point

    for(300;) // run forever
    {
        std::cout << *++g;  // increment to the next digit and print
    }
}

Solution

  • You are stating that you generating 300 digits, however this for-loop is broken:

    for(300;)
    

    It is not valid C++ code, as a for-loop is structured like this:

    for ( declaration ; expression ; increment)
    

    While all 3 segments are optional, you do need at least two semicolons (;) for a valid syntax.


    To achieve a for loop that repeats a sequence 300 times you would need a for loop-like this:

    for (int i = 0; i < 300; ++i)