// pi.cpp

#include <iostream>
#include <vector>
using namespace std;

typedef vector<long> N;
int L;

N num(int v, int place=0) {
	N a(L+1,0);
	a[place]=v;
	return a;
}

N norm(N a) {
	for (int i=L; i>0; i--) {
		long k=a[i]>=0 ? a[i]/10 : -((9-a[i])/10);
		a[i]-=k*10; a[i-1]+=k;
	}
	return a;
}

bool operator>=(const N &a, const N &b) {
	for (int i=0; i<=L; i++) if (a[i]!=b[i]) return a[i]>b[i];
	return true;
}

N operator+(N a, const N &b) {
	for (int i=0; i<=L; i++) a[i]+=b[i];
	return norm(a);
}

N operator-(N a, const N &b) {
	for (int i=0; i<=L; i++) a[i]-=b[i];
	return norm(a);
}

N operator*(N a, long m) {
	for (int i=0; i<=L; i++) a[i]*=m;
	return norm(a);
}

N operator*(const N &a, const N &b) {
	N c(L+1,0);
	for (int i=0; i<=L; i++)
		for (int j=0; i+j<=L; j++) c[i+j]+=a[i]*b[j];
	return norm(c);
}

N operator/(N r, const N &b) {
	N q(L+1,0);
	for (int i=0; i<=L; i++) {
		while (r>=b) { r=r-b; q[i]++; }
		r=r*10;
	}
	return q;
}

N sqrt(const N &a) {
	N x=num(1)+a;
	N old;
	do {
		old=x;
		x=(x+a/x)*num(5,1);
	}
	while (!(x>=old));
	return old;
}

int main() {
	int places;
	cout << "number of decimal places : ";
	if (!(cin >> places) || places<1) return 1;
	L=places+10;
	N one=num(1);
	N y=sqrt(num(2))-one;
	N a=num(6)-(y+one)*4;
	N old;
	int k=0;
	cout << "k  =";
	do {
		cout << " " << k << flush;
		old=a;
		N f=sqrt(sqrt(one-y*y*y*y));
		y=(one-f)/(one+f);
		N p=one+y;
		a=a*p*p*p*p-y*(p+y*y)*(1L<<(2*k+3));
		k++;
	}
	while (a!=old);
	N pi=one/a;
	cout << endl << endl;
	for (int i=0; i<=places; i++) {
		cout << pi[i];
		if (i==0) cout << '.' << endl;
		else if (i%50==0) cout << ' ' << endl;
		else if (i%10==0) cout << ' ';
	}
	cout << "\nready. (mhebel)\n";
	return 0;
}

  Pi mit 10000 Nachkommastellen (PDF)

   zurück