File: nth_prime_tiny.cpp

package info (click to toggle)
primecount 8.0%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,640 kB
  • sloc: cpp: 21,835; ansic: 121; sh: 99; makefile: 89
file content (70 lines) | stat: -rw-r--r-- 1,888 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
///
/// @file   nth_prime_tiny.cpp
/// @brief  Test the nth_prime(n) function for tiny values of n.
///         If n <= pi(PiTable::max_cached()) then nth_prime(n) uses
///         a lookup table under the hood and does not use any of
///         the advanced prime counting function implementations.
///         Large nth_prime(n) computations are tested in
///         test/api/nth_prime.cpp.
///
/// Copyright (C) 2023 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primecount.hpp>
#include <primesieve.hpp>
#include <PiTable.hpp>

#include <stdint.h>
#include <iostream>
#include <cstdlib>
#include <random>

using namespace primecount;

int main()
{
  int64_t n;

  // nth_prime(-1) must throw an exception
  try {
    n = -1;
    int64_t res = nth_prime(n);
    std::cout << "nth_prime(" << n << ") = " << res << "   ERROR\n";
    std::exit(1);
  }
  catch (const primecount_error& e) {
    std::cout << "nth_prime(" << n << ") = OK, caught exception: " << e.what() << "\n";
  }

  // nth_prime(0) must throw an exception
  try {
    n = 0;
    int64_t res = nth_prime(n);
    std::cout << "nth_prime(" << n << ") = " << res << "   ERROR\n";
    std::exit(1);
  }
  catch (const primecount_error& e) {
    std::cout << "nth_prime(" << n << ") = OK, caught exception: " << e.what() << "\n";
  }

  primesieve::iterator iter;
  int64_t max_n_tiny = PiTable::pi_cache(PiTable::max_cached());

  for (n = 1; n <= max_n_tiny; n++)
  {
    int64_t res1 = nth_prime(n);
    int64_t res2 = iter.next_prime();
    bool OK = (res1 == res2);
    std::cout << "nth_prime(" << n << ") = " << res1 << "   " << (OK ? "OK" : "ERROR") << "\n";
    if (!OK)
      std::exit(1);
  }

  std::cout << std::endl;
  std::cout << "All tests passed successfully!" << std::endl;

  return 0;
}