Strong and weak primes: Difference between revisions

Content added Content deleted
(Refactored C++ code)
Line 311: Line 311:
#include "prime_sieve.hpp"
#include "prime_sieve.hpp"


const int limit1 = 1000000;
int main() {
const int limit1 = 1000000;
const int limit2 = 10000000;
const int limit2 = 10000000;
const int max_print[2] = { 36, 37 };
const int array_size = limit2 + 100;


class prime_info {
// find the prime numbers up to array_size
public:
prime_sieve sieve(array_size);
explicit prime_info(int max) : max_print(max) {}

void add_prime(int prime) {
++count2;
if (prime < limit1)
++count1;
if (count2 <= max_print) {
if (count2 > 1)
out << ' ';
out << prime;
}
}
void print(std::ostream& os, const char* name) const {
os << "First " << max_print << " " << name << " primes: " << out.str() << '\n';
os << "Number of " << name << " primes below " << limit1 << ": " << count1 << '\n';
os << "Number of " << name << " primes below " << limit2 << ": " << count2 << '\n';
}
private:
int max_print;
int count1 = 0;
int count2 = 0;
std::ostringstream out;
};

int main() {
prime_sieve sieve(limit2 + 100);


// write numbers with groups of digits separated according to the system default locale
// write numbers with groups of digits separated according to the system default locale
std::cout.imbue(std::locale(""));
std::cout.imbue(std::locale(""));
std::cout << std::fixed;


// count and print strong/weak prime numbers
// count and print strong/weak prime numbers
prime_info strong_primes(36);
int count1[2] = { 0 };
prime_info weak_primes(37);
int count2[2] = { 0 };
std::ostringstream out[2];
const char* strength[2] = { "strong", "weak" };
int p1 = 2, p2 = 3;
int p1 = 2, p2 = 3;
for (int p3 = 5; p2 < limit2; ++p3) {
for (int p3 = 5; p2 < limit2; ++p3) {
Line 334: Line 355:
continue;
continue;
int diff = p1 + p3 - 2 * p2;
int diff = p1 + p3 - 2 * p2;
int index = diff < 0 ? 0 : (diff > 0 ? 1 : -1);
if (diff < 0)
if (index != -1) {
strong_primes.add_prime(p2);
++count2[index];
else if (diff > 0)
if (p2 < limit1)
weak_primes.add_prime(p2);
++count1[index];
if (count2[index] <= max_print[index]) {
if (count2[index] > 1)
out[index] << ' ';
out[index] << p2;
}
}
p1 = p2;
p1 = p2;
p2 = p3;
p2 = p3;
}
}
strong_primes.print(std::cout, "strong");
for (int i = 0; i < 2; ++i) {
weak_primes.print(std::cout, "weak");
std::cout << "First " << max_print[i] << " " << strength[i] << " primes: " << out[i].str() << '\n';
std::cout << "Number of " << strength[i] << " primes below " << limit1 << ": " << count1[i] << '\n';
std::cout << "Number of " << strength[i] << " primes below " << limit2 << ": " << count2[i] << '\n';
}
return 0;
return 0;
}</lang>
}</lang>