Truncatable primes: Difference between revisions
Content added Content deleted
(Added Rust solution) |
m (C++ - renamed class) |
||
Line 529: | Line 529: | ||
=={{header|C++}}== |
=={{header|C++}}== |
||
<lang cpp>#include <iostream> |
<lang cpp>#include <iostream> |
||
#include " |
#include "prime_sieve.hpp" |
||
bool is_left_truncatable(const |
bool is_left_truncatable(const prime_sieve& sieve, int p) { |
||
for (int n = 10, q = p; p > n; n *= 10) { |
for (int n = 10, q = p; p > n; n *= 10) { |
||
if (!sieve.is_prime(p % n) || q == p % n) |
if (!sieve.is_prime(p % n) || q == p % n) |
||
Line 540: | Line 540: | ||
} |
} |
||
bool is_right_truncatable(const |
bool is_right_truncatable(const prime_sieve& sieve, int p) { |
||
for (int q = p/10; q > 0; q /= 10) { |
for (int q = p/10; q > 0; q /= 10) { |
||
if (!sieve.is_prime(q)) |
if (!sieve.is_prime(q)) |
||
Line 552: | Line 552: | ||
// find the prime numbers up to the limit |
// find the prime numbers up to the limit |
||
prime_sieve sieve(limit + 1); |
|||
int largest_left = 0; |
int largest_left = 0; |
||
Line 576: | Line 576: | ||
}</lang> |
}</lang> |
||
Contents of |
Contents of prime_sieve.hpp: |
||
<lang cpp>#ifndef |
<lang cpp>#ifndef PRIME_SIEVE_HPP |
||
#define |
#define PRIME_SIEVE_HPP |
||
#include <algorithm> |
#include <algorithm> |
||
Line 587: | Line 587: | ||
* See https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes. |
* See https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes. |
||
*/ |
*/ |
||
class |
class prime_sieve { |
||
public: |
public: |
||
explicit |
explicit prime_sieve(size_t); |
||
bool is_prime(size_t) const; |
bool is_prime(size_t) const; |
||
private: |
private: |
||
Line 600: | Line 600: | ||
* @param limit the maximum integer that can be tested for primality |
* @param limit the maximum integer that can be tested for primality |
||
*/ |
*/ |
||
inline |
inline prime_sieve::prime_sieve(size_t limit) { |
||
limit = std::max(size_t(3), limit); |
limit = std::max(size_t(3), limit); |
||
is_prime_.resize(limit/2, true); |
is_prime_.resize(limit/2, true); |
||
Line 620: | Line 620: | ||
* @return true if the integer is prime |
* @return true if the integer is prime |
||
*/ |
*/ |
||
inline bool |
inline bool prime_sieve::is_prime(size_t n) const { |
||
if (n == 2) |
if (n == 2) |
||
return true; |
return true; |