Calculating Value of $\pi$ using Zeta Function on C++ spits error

150 Views Asked by At

I'm not sure if this is the correct place to ask this, but surely it's not a programming question.

$$\zeta (s) = \prod \limits_{p \space prime} \left ( 1 - \frac{1}{p^s} \right)^{-1}$$

So, as we know that $\zeta (2)$ converges to $\frac {\pi^2} 6$,

I was writing a blog to show that the value of pi can also be calculated using Prime Numbers, so, to convince the people, I was creating a program for that.

$$ \pi = \sqrt{6 \times \prod \limits_{p \space prime} \left ( 1- \frac 1 {p^2} \right)^{-1}}$$

But, for highly precise values of the number of primes (up to 10), the value increases to 3.33 same with 100 digits of pi. Here's my C++ Program.

#include <iostream>
#include <conio.h>
#include <math.h>

using namespace std;

int prime(int n);
int primep(int n);
long double euler(int n, int s);

int main()
{
    int n,s=2;
    long double t=1;

    cout<<"Enter precision"<<endl;
    cin>>n;

    for(int i=1; i<=n; i++)
    {
        t *= euler(primep(i), s);
    }

    t *= 6;

    t = sqrt(t);

    cout<<"The value of pi is"<<t<<endl;

    getch();
return 0;
}

/* this function returns the next prime number after a given number,
   if the given number is prime, then it just returns that number */
int prime(int n)
{

    for(int i=n; i>=n; i++)
    {
        for(int j=2; j<n; j++)
        {
            if(i%j==0)
                {
                    j=2;
                    i++;
                }
        }

    return i;
    break;
    }

}


/* This function is prime++ which checks if a given numbers is a prime
or not, if it's a prime, then it finds the next prime, or if, it's 
composite, then it finds the next prime number */

int primep(int n)
{
    int x=prime(n);
    if (x==n)
    return prime(n+1);
    else
    return x;
}

/* To calculate each term of product */
long double euler(int n, int s)
{
    return (1/(1-(1/(pow(n,s)))));
}

Pi Calculator using Prime Numbers and Zeta function enter image description here

Thanks :)

1

There are 1 best solutions below

3
On BEST ANSWER

In your Euler product loop you are including certain primes (e.g. 5) more than once. I suggest you just create a list of primes first, and then compute the Euler product. This would also be much more efficient.