0

The formula is listed in the following article: https://en.wikipedia.org/wiki/Formula_for_primes. I am trying to implement it but to no success, for whatever reason the code is producing number which seem to be nth power of two + 1, which is obviously not what I want to achieve.

#include <iostream>
#include <cmath>

using namespace std;

int nth_prime(int n) {
    double s = 1;
    
    for (int i = 1; i <= pow(2, n); i++) {
        double c = 0;
        for (int j = 1; j <= i; j++) {
            double f = (tgamma(j)+1)/j;
            c+=floor(pow(cos(M_PI*f), 2));
        }
        s+=floor(pow(n/c, 1/n));
    }

    return s;

}

int main() {

    int n;

    while (cin >> n) {
        cout << nth_prime(n) << endl;
    }
    return 0;
}
wiktort1
  • 330
  • 2
  • 4
  • Well first as a general rule for C++: [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). – oraqlle Sep 27 '22 at 10:22
  • i know that perfectly well but for this program any conflicts are unlikely and i dont have to type std:: every time – wiktort1 Sep 27 '22 at 10:27
  • Then use the `using` declaration to import the needed members. eg. `using std::cout` – oraqlle Sep 27 '22 at 10:29
  • alright, changed it just for the sake of using good practices but obviously this doesn't solve my issue. – wiktort1 Sep 27 '22 at 10:30
  • 1
    You've done integer division in some places where double of floating-point division is needed. [Integer vs Floating-Point Division](https://www.godbolt.org/z/n3E6xMz7M) and [Improved example](https://www.godbolt.org/z/EMq9sz9Ke) (still broken for 7th+ primes) – oraqlle Sep 27 '22 at 10:56
  • Also don't expect this to go right for larger 'n' values, you will run into precission problems. – Pepijn Kramer Sep 27 '22 at 11:03
  • (see comment by oraqlle)... and using float functions in integer context gets you similar issues. – Yunnosch Sep 27 '22 at 11:03

0 Answers0