int prIsPrime(VMGlobals *g, int numArgsPushed) { PyrSlot *a; int n, p, sqrtn, i; a = g->sp; n = slotRawInt(a); SetNil(a); if (n <= 2) { if (n == 2) { SetTrue(a); } else { SetFalse(a); } } else if (n <= nthPrime(NUMPRIMES-1)) { // do a search of the primes table i = findPrime(n); if (i >= 0) { SetTrue(a); } else { SetFalse(a); } } else { #ifdef SC_WIN32 sqrtn = (int)sqrt(static_cast<double>(n)); #else sqrtn = (int)sqrt(n); #endif for (i=0; i<NUMPRIMES; ++i) { p = nthPrime(i); if (n % p == 0) { SetFalse(a); break; } if (p >= sqrtn) { SetTrue(a); break; } } } return errNone; }
int main(void) { int result = nthPrime(10000); printf("%d\n", result); return result; // Answer: 104743 }
long nextPrime(int n) { // binary search of primes table int i, p, lo = 0, hi = NUMPRIMES-1; while (hi>=lo) { i = (lo + hi) >> 1; p = nthPrime(i); if (n==p) return i; if (n<p) hi = i - 1; else lo = i + 1; } return sc_clip(lo, 0, NUMPRIMES-1); }
long findPrime(int n) { // binary search of primes table int i, p, lo = 0, hi = NUMPRIMES-1; while (hi>=lo) { i = (lo + hi) >> 1; p = (int)nthPrime(i); // kengo: if (n==p) return i; if (n<p) hi = i - 1; else lo = i + 1; } return -1; }
int prNthPrime(VMGlobals *g, int numArgsPushed) { PyrSlot *a; int n, p; a = g->sp; n = slotRawInt(a); p = nthPrime(n); if (p == 0) { SetNil(a); } else { SetInt(a, p); } return errNone; }
int prIndexOfPrime(VMGlobals *g, int numArgsPushed) { PyrSlot *a; int n, p; a = g->sp; n = slotRawInt(a); if (n <= 2) { if (n == 2) { SetInt(a, 0); } else { SetNil(a); } } else if (n <= nthPrime(NUMPRIMES-1)) { p = findPrime(n); if (p < 0) { SetNil(a); } else { SetInt(a, p); } } else { SetNil(a); } return errNone; }
uint64_t PrimeSieve::nthPrime(uint64_t n) { return nthPrime(0, n); }
ProblemInteger run(void) { return nthPrime(10001); }
ProblemInteger check(void) { return nthPrime(6); }