Jump to content

Ramanujan primes: Difference between revisions

Added C++ solution
(Added C++ solution)
Line 24:
:*   The Wikipedia entry: [https://en.wikipedia.org/wiki/Ramanujan_prime Ramanujan_prime].
 
 
=={{header|C++}}==
{{trans|Julia}}
<lang cpp>#include <chrono>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <vector>
 
class prime_counter {
public:
explicit prime_counter(int limit);
int prime_count(int n) const { return n < 1 ? 0 : count_.at(n); }
 
private:
std::vector<int> count_;
};
 
prime_counter::prime_counter(int limit) : count_(limit, 1) {
if (limit > 0)
count_[0] = 0;
if (limit > 1)
count_[1] = 0;
for (int i = 4; i < limit; i += 2)
count_[i] = 0;
for (int p = 3, sq = 9; sq < limit; p += 2) {
if (count_[p]) {
for (int q = sq; q < limit; q += p << 1)
count_[q] = 0;
}
sq += (p + 1) << 2;
}
std::partial_sum(count_.begin(), count_.end(), count_.begin());
}
 
int ramanujan_max(int n) {
return static_cast<int>(std::ceil(4 * n * std::log(4 * n)));
}
 
int ramanujan_prime(const prime_counter& pc, int n) {
int max = ramanujan_max(n);
for (int i = max; i >= 0; --i) {
if (pc.prime_count(i) - pc.prime_count(i / 2) < n)
return i + 1;
}
return 0;
}
 
int main() {
std::cout.imbue(std::locale(""));
auto start = std::chrono::high_resolution_clock::now();
prime_counter pc(1 + ramanujan_max(100000));
for (int i = 1; i <= 100; ++i) {
std::cout << std::setw(5) << ramanujan_prime(pc, i)
<< (i % 10 == 0 ? '\n' : ' ');
}
std::cout << '\n';
for (int n = 1000; n <= 100000; n *= 10) {
std::cout << "The " << n << "th Ramanujan prime is " << ramanujan_prime(pc, n)
<< ".\n";
}
auto end = std::chrono::high_resolution_clock::now();
std::cout << "\nElapsed time: "
<< std::chrono::duration<double>(end - start).count() * 1000
<< " milliseconds\n";
}</lang>
 
{{out}}
<pre>
2 11 17 29 41 47 59 67 71 97
101 107 127 149 151 167 179 181 227 229
233 239 241 263 269 281 307 311 347 349
367 373 401 409 419 431 433 439 461 487
491 503 569 571 587 593 599 601 607 641
643 647 653 659 677 719 727 739 751 769
809 821 823 827 853 857 881 937 941 947
967 983 1,009 1,019 1,021 1,031 1,049 1,051 1,061 1,063
1,087 1,091 1,097 1,103 1,151 1,163 1,187 1,217 1,229 1,249
1,277 1,289 1,297 1,301 1,367 1,373 1,423 1,427 1,429 1,439
 
The 1,000th Ramanujan prime is 19,403.
The 10,000th Ramanujan prime is 242,057.
The 100,000th Ramanujan prime is 2,916,539.
 
Elapsed time: 46.0828 milliseconds
</pre>
 
=={{header|Go}}==
1,777

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.