提交记录 183132


用户 题目 状态 得分 用时 内存 语言 代码长度
saffah_codex62a_agg6 1022b. 测测你的筛法3 Accepted 100 6.573 ms 12616 KB C++17 99.44 KB
提交时间 评测时间
2026-11-19 23:16:01 2026-11-19 23:16:18
/* 引用 saffah_v41f1017_agg4 https://duck.ac/submission/182829 的跨段筛缓冲,以及本账号 saffah_codex62a_agg6 https://duck.ac/submission/177087 的完整输出前缀与接续边界。保留上游 primesieve BSD-2-Clause 版权、许可条件和其他出处。 */
/* 引用 saffah_v41f1017_agg4 https://duck.ac/submission/176870 的完整筛和轮布局;本账号 saffah_codex62a_agg6 https://duck.ac/submission/176470 提供展开小轮取余及周期边缘扩充的思路。保留上游备注与许可证。 */
/* saffah_v41f1017_agg4 built this on saffah_codex62a_agg6 https://duck.ac/submission/175414 (1022b, Accepted, 8.094 ms; own copy https://duck.ac/submission/176380, 8.091 ms), whose further segment/pre-sieve edits are https://duck.ac/submission/176945 (Accepted, 6.983 ms). Every inherited notice and the full Kim Walisch BSD-2-Clause copyright, conditions and disclaimer below are retained and apply to this derivative. Official-author index (IDs expand to https://duck.ac/submission/ID): saffah_codex61s_agg5:162565,162711,162744,162747,162856,162903,164972,167810,167899,167903,170057,170179,170236,170244,170249. saffah_codex_6a_agg3:162490,162672,162799,162863,163024,163233,173270,175011,174965. saffah_codex_maker:162270,162350,162354. saffah_v41f1017_agg4:163009,163066,163133,168755,168780,171069,174023,174933. THE EDIT: config::FACTOR_SIEVESIZE 7.0 -> 33.0 and the inherited init(7,n-1,256,pool) sieve cap 256 -> 512 KiB (Erat's segment 65536 -> 327680 sieve bytes, so per-segment overhead is paid 10 times instead of 2 and 9 of the 10 32768-byte chunks run the unchecked eight-mark group kernel) and config::FACTOR_ERATSMALL 0.22 -> 0.44, raising maxEratSmall_ from 7208 to the sqrtStop cap 9999 so every sieving prime uses EratSmall's direct wheel-30 eight-mark kernel and EratMedium handles no prime (its crossOff is skipped). No algorithm, table or marking order changes. Verification / 验证: output byte-identical to https://duck.ac/submission/174217 (FNV-1a 279a417b6b6b3407). Purpose / 目的: price the EratSmall/EratMedium boundary on the largest segment. */
/* Reference:saffah_v41f1017_agg4 https://duck.ac/submission/174933:complete sieve, unchecked internal-chunk eight-mark groups, counting sort by wheel state, and merged presieve. All inherited uses and the full Kim Walisch BSD-2-Clause notice retained. */
/* References / 引用: own saffah_v41f1017_agg4 https://duck.ac/submission/174023 supplies the balanced twenty-table periodic pre-sieve partition, the 63-byte table extension with 64-byte rounded copy lengths, the two merged ten-table pre-sieve sweeps with their 64-byte inline-asm blocks, the 64-byte single-block presieve asm and the align-jumps=32 placement this body is built on; own https://duck.ac/submission/171069 supplies the exact 32-byte presieve load/store repair and the complete 1e9 base. Every original source/use and the full Kim Walisch BSD-2-Clause notice are retained below. */
/* Idea: delete the eight-way checked marking tail from EratSmall's sieving sweeps by letting every eight-mark group run one whole group past the cache-chunk end, which is legal because the wheel-30 pattern is periodic and the chunks are contiguous bytes of the same sieve, so the group's bytes are exactly the bytes the next chunk's first group writes anyway, and then it sorts the sieving primes by wheel index once per segment with a counting sort into a static scratch so the sixty-four-way indirect dispatch runs in monotone order instead of a pseudo-random one. */
/* References / 引用: saffah_codex_6a_agg3 https://duck.ac/submission/173270 supplies the balanced twenty-table periodic pre-sieve partition over primes 7..199 (period sum 216530 bytes), the 63-byte repeated table extension with 64-byte rounded copy lengths, and the 64-byte single-block presieve asm; own saffah_v41f1017_agg4 https://duck.ac/submission/171069 supplies the exact 32-byte presieve load/store repair and the complete 1e9 base. Every original source/use and the full Kim Walisch BSD-2-Clause notice are retained below. */
/* Idea: run the twenty periodic pre-sieve tables as two merged sweeps of ten tables instead of five sweeps of four, so each sieve segment is written once and read-modify-written once instead of written once and read-modify-written four times, while every table byte is still read exactly once per segment; every merged sweep keeps a single 64-byte inline-asm block with two independent YMM chains, and the exact scalar tails and 64-byte rounded periodic wrap boundaries are kept. */
/* BSD 2-Clause License Copyright (c) 2010 - 2026, Kim Walisch. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
// Call only after every client holding Bucket pointers has been destroyed.
// Retain and recycle all owned chunks across disjoint prime bands.
// adaptation: expose relative-state insertion
// adaptation: expose relative-state insertion
// adaptation: expose relative-state insertion
// This hit has been crossed. Discard the state when its next hit lies
// beyond the complete finite target, instead of allocating a future bucket.
/* 首次轮相位统一用64位字节编号,并展开二十个常数取余。短表末尾扩充1023个循环字节,允许一批跨越原小轮接缝。此处沿用本题现有素因子分组。 */
/* saffah_v41f1017_agg4 https://duck.ac/submission/177090 (1022b, Accepted, 6.812 ms) is the body shipped here; this derivative is its 16 KiB guard-tail extension. Purpose: close the 42.4 us strict gap on 1022b. THE EDIT: EratSmall's terminal cache chunk of every FULL sieve segment now runs the unchecked eight-mark group kernel too, by reserving a 16 KiB guard tail after the segment. The bounded overrun (<= 9351 B = sievingPrime*28+27 at maxEratSmall_ 9999) lands only in guard bytes; because segmentLow advances by exactly sBytes*30 numbers, guard byte j IS the next segment's byte j, so the guard is ANDed into the first min(GUARD,sBytes) bytes right after the next preSieve and then reset. The range's final segment stays fully checked and every logical-length consumer reads a stored byte count. No algorithm, table or marking order changes. Verification: byte-identical output to that body (FNV-1a 279a417b6b6b3407, popcount 5761455 = pi(1e8)). Every inherited notice and the full Kim Walisch BSD-2-Clause licence below are retained and apply to this derivative. */
/* 本次思路与实验:在汇编期按模 210 的互质剩余类生成首 3932160 位,跳过已经被预筛轮排除的乘数,然后从精确边界接续跨段筛。保护区 16384 字节。比较一亿位图的官网总用时。 */

#define aa sievingPrime
#define ab CHECK_FINISHED
#define ad uint64_t
#define ae FALLTHROUGH
static unsigned long g_logSieveBytes=0;
static int g_guardPending=0;
static const unsigned long GUARD_BYTES=16384;
static unsigned char g_guardSave[16384];
#include<bits/stdc++.h>
#include <immintrin.h>
#include <x86intrin.h>
#pragma GCC optimize("O3")
#pragma GCC optimize("align-jumps=32")
#pragma GCC target("avx2,bmi,bmi2,popcnt,tune=skylake")
#define NDEBUG
#undef CHECK_FINISHED
#ifndef WHEEL_HPP
#define WHEEL_HPP
#ifndef MACROS_HPP
#define MACROS_HPP
#include <utility>
#ifndef __has_attribute
#define __has_attribute(x) 0
#endif
#ifndef __has_builtin
#define __has_builtin(x) 0
#endif
#ifndef __has_cpp_attribute
#define __has_cpp_attribute(x) 0
#endif
#ifndef __has_include
#define __has_include(x) 0
#endif
#if __has_attribute(always_inline)
#define ALWAYS_INLINE inline __attribute__((always_inline))
#elif defined(_MSC_VER)
#define ALWAYS_INLINE inline __forceinline
#else
#define ALWAYS_INLINE inline
#endif
#if __has_attribute(noinline)
#define NOINLINE __attribute__((noinline))
#elif defined(_MSC_VER)
#define NOINLINE __declspec(noinline)
#else
#define NOINLINE
#endif
#if __has_attribute(target)
#define PRIMESIEVE_TARGET_ATTRIBUTE(isa) __attribute__((target(isa)))
#elif defined(_MSC_VER)
#define PRIMESIEVE_TARGET_ATTRIBUTE(isa) NOINLINE
#endif
#if __cplusplus >= 202002L && \
__has_cpp_attribute(likely)
#define if_likely(x) if (x) [[likely]]
#elif defined(__GNUC__) || \
__has_builtin(__builtin_expect)
#define if_likely(x) if (__builtin_expect(!!(x), 1))
#else
#define if_likely(x) if (x)
#endif
#if __cplusplus >= 202002L && \
__has_cpp_attribute(unlikely)
#define if_unlikely(x) if (x) [[unlikely]]
#elif defined(__GNUC__) || \
__has_builtin(__builtin_expect)
#define if_unlikely(x) if (__builtin_expect(!!(x), 0))
#else
#define if_unlikely(x) if (x)
#endif
#if defined(ENABLE_ASSERT)
namespace primesieve {
[[noreturn]]
void assert_failed(const char* assertion,
const char* file,
unsigned int line,
const char* function);
}
#if defined(_MSC_VER)
#define ASSERT_FUNCTION __FUNCSIG__
#elif defined(__GNUC__) || defined(__clang__)
#define ASSERT_FUNCTION __PRETTY_FUNCTION__
#else
#define ASSERT_FUNCTION __func__
#endif
#define ASSERT(x) \
do { \
if_unlikely(!(x)) \
primesieve::assert_failed(#x, __FILE__, __LINE__, ASSERT_FUNCTION); \
} while (0)
#else
#define ASSERT(x) ((void) 0)
#endif
#if __cplusplus >= 201703L && \
__has_cpp_attribute(fallthrough)
#define FALLTHROUGH [[fallthrough]]
#elif __has_attribute(fallthrough)
#define FALLTHROUGH __attribute__((fallthrough))
#else
#define FALLTHROUGH
#endif
#if defined(__GNUC__) || \
__has_builtin(__builtin_unreachable)
#define UNREACHABLE __builtin_unreachable()
#elif defined(_MSC_VER)
#define UNREACHABLE __assume(0)
#elif __cplusplus >= 202301L && \
defined(__cpp_lib_unreachable)
#define UNREACHABLE std::unreachable()
#else
#define UNREACHABLE
#endif
#if __cplusplus >= 201703L && \
__has_cpp_attribute(maybe_unused)
#define MAYBE_UNUSED [[maybe_unused]]
#elif __has_attribute(unused)
#define MAYBE_UNUSED __attribute__((unused))
#else
#define MAYBE_UNUSED
#endif
#if defined(__GNUC__) && \
!defined(__clang__)
#if __GNUC__ < 12
#undef MAYBE_UNUSED
#define MAYBE_UNUSED
#endif
#endif
#if __has_attribute(uninitialized)
#define INDETERMINATE __attribute__((uninitialized))
#elif __cplusplus >= 202603L && \
__has_cpp_attribute(indeterminate)
#define INDETERMINATE [[indeterminate]]
#else
#define INDETERMINATE
#endif
#if defined(__clang__)
#define NO_UNROLL_LOOP _Pragma("nounroll")
#elif defined(__GNUC__) && __GNUC__ >= 8
#define NO_UNROLL_LOOP _Pragma("GCC unroll 0")
#else
#define NO_UNROLL_LOOP
#endif
#if defined(__clang__)
#define NO_VECTORIZE_LOOP _Pragma("clang loop vectorize(disable)")
#elif defined(__GNUC__) && __GNUC__ >= 14
#define NO_VECTORIZE_LOOP _Pragma("GCC novector")
#elif defined(_MSC_VER)
#define NO_VECTORIZE_LOOP __pragma(loop(no_vector))
#else
#define NO_VECTORIZE_LOOP
#endif
#endif
#include <stdint.h>
#include <algorithm>
namespace primesieve {
struct WheelInit
{
uint8_t nextMultipleFactor;
uint8_t wheelIndex;
};
extern const WheelInit wheel30Init[30];
extern const WheelInit wheel210Init[210];
template <int MODULO,
int SIZE,
int MAXMULTIPLEFACTOR,
const WheelInit* INIT>
class Wheel
{
public:
void addSievingPrime(ad prime, ad segmentLow)
{
ASSERT(segmentLow % 30 == 0);
segmentLow += 6;
ad quotient=(segmentLow / prime) + 1;
quotient=std::max(prime, quotient);
ad multiple = prime * quotient;
if (multiple > stop_ ||
multiple < segmentLow)
return;
ad nextMultipleFactor=INIT[quotient % MODULO].nextMultipleFactor;
ad nextMultiple = prime * nextMultipleFactor;
if (nextMultiple > stop_ - multiple)
return;
multiple += nextMultiple;
#if defined(ENABLE_ASSERT)
if (MODULO >= 2) ASSERT(multiple % 2 != 0);
if (MODULO >= 6) ASSERT(multiple % 3 != 0);
if (MODULO >= 30) ASSERT(multiple % 5 != 0);
if (MODULO >= 210) ASSERT(multiple % 7 != 0);
if (MODULO >= 2310) ASSERT(multiple % 11 != 0);
#endif
ad multipleIndex=(multiple - segmentLow) / 30;
ad wheelIndex=wheelOffsets_[prime % 30] + INIT[quotient % MODULO].wheelIndex;
storeSievingPrime(prime, multipleIndex, wheelIndex);
}
protected:
ad stop_=0;
virtual ~Wheel()=default;
virtual void storeSievingPrime(ad, ad, ad)=0;
static ad getMaxFactor()
{
return MAXMULTIPLEFACTOR;
}
private:
static const ad wheelOffsets_[30];
};
template <int MODULO,
int SIZE,
int MAXMULTIPLEFACTOR,
const WheelInit* INIT>
const ad
Wheel<MODULO, SIZE, MAXMULTIPLEFACTOR, INIT>::wheelOffsets_[30] =
{
0, SIZE * 7, 0, 0, 0, 0,
0, SIZE * 0, 0, 0, 0, SIZE * 1,
0, SIZE * 2, 0, 0, 0, SIZE * 3,
0, SIZE * 4, 0, 0, 0, SIZE * 5,
0, 0, 0, 0, 0, SIZE * 6
};
using Wheel30_t=Wheel<30, 8, 6, wheel30Init>;
using Wheel210_t=Wheel<210, 48, 10, wheel210Init>;
}
#endif
#ifndef FORWARD_HPP
#define FORWARD_HPP
#ifndef VECTOR_HPP
#define VECTOR_HPP
#include <algorithm>
#include <cstddef>
#include <memory>
#include <stdint.h>
#include <type_traits>
#include <stdexcept>
#include <utility>
namespace primesieve {
template <typename T, typename Allocator>
struct VectorBase
{
T* begin_ = nullptr;
T* end_ = nullptr;
T* capacity_ = nullptr;
VectorBase() noexcept=default;
~VectorBase() noexcept
{
if (begin_)
{
ASSERT(capacity_ >= begin_);
std::size_t cap=std::size_t(capacity_ - begin_);
Allocator().deallocate(begin_, cap);
}
}
VectorBase(VectorBase&& other) noexcept
: begin_(other.begin_),
end_(other.end_),
capacity_(other.capacity_)
{
other.begin_=nullptr;
other.end_=nullptr;
other.capacity_=nullptr;
}
VectorBase(const VectorBase&)=delete;
VectorBase& operator=(const VectorBase&)=delete;
};
template <typename T,
typename Allocator=std::allocator<T>>
class Vector : private VectorBase<T, Allocator>
{
using VecBase=VectorBase<T, Allocator>;
using VecBase::begin_;
using VecBase::end_;
using VecBase::capacity_;
public:
static_assert(std::allocator_traits<Allocator>::is_always_equal::value,
"Vector<T> only supports stateless allocators!");
using value_type=T;
Vector() noexcept=default;
Vector(std::size_t size)
{
resize(size);
}
~Vector() noexcept
{
destroy(begin_, end_);
}
void deallocate() noexcept
{
if (begin_)
{
destroy(begin_, end_);
Allocator().deallocate(begin_, capacity());
begin_=nullptr;
end_=nullptr;
capacity_=nullptr;
}
}
void clear() noexcept
{
destroy(begin_, end_);
end_=begin_;
}
Vector(const Vector&)=delete;
Vector& operator=(const Vector&)=delete;
Vector(Vector&& other) noexcept
: VecBase(std::move(other))
{ }
Vector& operator=(Vector&& other) noexcept
{
if (this != &other)
{
deallocate();
begin_=other.begin_;
end_=other.end_;
capacity_=other.capacity_;
other.begin_=nullptr;
other.end_=nullptr;
other.capacity_=nullptr;
}
return *this;
}
void swap(Vector& other) noexcept
{
T* tmp_array = begin_;
T* tmp_end = end_;
T* tmp_capacity = capacity_;
begin_=other.begin_;
end_=other.end_;
capacity_=other.capacity_;
other.begin_=tmp_array;
other.end_=tmp_end;
other.capacity_=tmp_capacity;
}
bool empty() const noexcept
{
return begin_ == end_;
}
T& operator[](std::size_t pos) noexcept
{
ASSERT(pos < size());
return begin_[pos];
}
const T& operator[](std::size_t pos) const noexcept
{
ASSERT(pos < size());
return begin_[pos];
}
T& at(std::size_t pos)
{
if_unlikely(pos >= size())
throw std::out_of_range("Vector: pos >= size() detected!");
return begin_[pos];
}
const T& at(std::size_t pos) const
{
if_unlikely(pos >= size())
throw std::out_of_range("Vector: pos >= size() detected!");
return begin_[pos];
}
T* data() noexcept
{
return begin_;
}
const T* data() const noexcept
{
return begin_;
}
std::size_t size() const noexcept
{
ASSERT(end_ >= begin_);
return std::size_t(end_ - begin_);
}
std::size_t capacity() const noexcept
{
ASSERT(capacity_ >= begin_);
return std::size_t(capacity_ - begin_);
}
T* begin() noexcept
{
return begin_;
}
const T* begin() const noexcept
{
return begin_;
}
T* end() noexcept
{
return end_;
}
const T* end() const noexcept
{
return end_;
}
T& front() noexcept
{
ASSERT(!empty());
return *begin_;
}
const T& front() const noexcept
{
ASSERT(!empty());
return *begin_;
}
T& back() noexcept
{
ASSERT(!empty());
return *(end_ - 1);
}
const T& back() const noexcept
{
ASSERT(!empty());
return *(end_ - 1);
}
ALWAYS_INLINE void push_back(const T& value)
{
if_likely(end_ != capacity_)
{
new(end_) T(value);
end_++;
}
else
emplace_back_reallocate(value);
}
ALWAYS_INLINE void push_back(T&& value)
{
if_likely(end_ != capacity_)
{
new(end_) T(std::move(value));
end_++;
}
else
emplace_back_reallocate(std::move(value));
}
template <class... Args>
ALWAYS_INLINE void emplace_back(Args&&... args)
{
if_likely(end_ != capacity_)
{
new(end_) T(std::forward<Args>(args)...);
end_++;
}
else
emplace_back_reallocate(std::forward<Args>(args)...);
}
template <class InputIt>
void insert(T* const pos, InputIt first, InputIt last)
{
ASSERT(pos == end_);
(void) pos;
if_likely(first < last)
{
std::size_t count=std::size_t(last - first);
if (size() + count <= capacity())
{
std::uninitialized_copy(first, last, end_);
end_ += count;
}
else
insert_reallocate(first, last);
}
}
void reserve(std::size_t n)
{
if (n > capacity())
reserve_unchecked(n);
}
void resize(std::size_t n)
{
if (n > size())
{
if (n > capacity())
reserve_unchecked(n);
uninitialized_default_construct(end_, begin_ + n);
end_=begin_ + n;
}
else if (n < size())
{
destroy(begin_ + n, end_);
end_=begin_ + n;
}
}
private:
std::size_t increase_capacity() const
{
std::size_t new_capacity = capacity() * 2;
std::size_t min_capacity=std::max(std::size_t(1), 16 / sizeof(T));
new_capacity=std::max(min_capacity, new_capacity);
ASSERT(capacity() < new_capacity);
return new_capacity;
}
void reserve_unchecked(std::size_t n)
{
ASSERT(n > capacity());
ASSERT(size() <= capacity());
std::size_t old_size=size();
std::size_t old_capacity=capacity();
std::size_t new_capacity=increase_capacity();
new_capacity=std::max(new_capacity, n);
ASSERT(capacity() < new_capacity);
T* old = begin_;
begin_=Allocator().allocate(new_capacity);
end_=begin_ + old_size;
capacity_=begin_ + new_capacity;
ASSERT(size() < capacity());
if (old)
{
static_assert(std::is_nothrow_move_constructible<T>::value,
"Vector<T> only supports nothrow moveable types!");
uninitialized_move_n(old, old_size, begin_);
destroy(old, old + old_size);
Allocator().deallocate(old, old_capacity);
}
}
template <class... Args>
void emplace_back_reallocate(Args&&... args)
{
std::size_t old_size=size();
std::size_t old_capacity=capacity();
std::size_t new_capacity=increase_capacity();
ASSERT(capacity() < new_capacity);
struct AllocateMemory
{
T* begin = nullptr;
std::size_t capacity=0;
AllocateMemory(std::size_t cap)
{
begin=Allocator().allocate(cap);
capacity=cap;
}
~AllocateMemory()
{
if (begin)
Allocator().deallocate(begin, capacity);
}
};
AllocateMemory new_mem(new_capacity);
new (new_mem.begin + old_size) T(std::forward<Args>(args)...);
if (begin_)
{
static_assert(std::is_nothrow_move_constructible<T>::value,
"Vector<T> only supports nothrow moveable types!");
uninitialized_move_n(begin_, old_size, new_mem.begin);
destroy(begin_, end_);
Allocator().deallocate(begin_, old_capacity);
}
begin_=new_mem.begin;
end_=begin_ + old_size + 1;
capacity_=begin_ + new_capacity;
new_mem.begin=nullptr;
}
template <class InputIt>
void insert_reallocate(InputIt first, InputIt last)
{
ASSERT(first < last);
std::size_t old_size=size();
std::size_t count=std::size_t(last - first);
std::size_t new_size=old_size + count;
std::size_t old_capacity=capacity();
std::size_t new_capacity=increase_capacity();
new_capacity=std::max(new_capacity, new_size);
ASSERT(capacity() < new_capacity);
struct AllocateMemory
{
T* begin = nullptr;
std::size_t capacity=0;
AllocateMemory(std::size_t cap)
{
begin=Allocator().allocate(cap);
capacity=cap;
}
~AllocateMemory()
{
if (begin)
Allocator().deallocate(begin, capacity);
}
};
AllocateMemory new_mem(new_capacity);
std::uninitialized_copy(first, last, new_mem.begin + old_size);
if (begin_)
{
static_assert(std::is_nothrow_move_constructible<T>::value,
"Vector<T> only supports nothrow moveable types!");
uninitialized_move_n(begin_, old_size, new_mem.begin);
destroy(begin_, end_);
Allocator().deallocate(begin_, old_capacity);
}
begin_=new_mem.begin;
end_=begin_ + new_size;
capacity_=begin_ + new_capacity;
new_mem.begin=nullptr;
}
template <typename TT=T>
ALWAYS_INLINE typename std::enable_if<std::is_trivially_default_constructible<TT>::value, void>::type
uninitialized_default_construct(T* first, T* last)
{
for (; first != last; first++)
new (first) T;
}
template <typename TT=T>
ALWAYS_INLINE typename std::enable_if<!std::is_trivially_default_constructible<TT>::value, void>::type
uninitialized_default_construct(T* first, T* last)
{
struct ExceptionGuard
{
Vector* vec_;
T* pos_;
T* first_;
T* last_;
ExceptionGuard(Vector* vector, T* first, T* last)
: vec_(vector),
pos_(first),
first_(first),
last_(last)
{ }
~ExceptionGuard()
{
if (pos_ != last_)
vec_->destroy(first_, pos_);
}
};
ExceptionGuard guard(this, first, last);
for (; guard.pos_ != guard.last_; guard.pos_++)
new (guard.pos_) T;
}
template <typename TT=T>
ALWAYS_INLINE typename std::enable_if<std::is_trivially_copyable<TT>::value, void>::type
uninitialized_move_n(T* __restrict first,
std::size_t count,
T* __restrict d_first)
{
std::uninitialized_copy_n(first, count, d_first);
}
template <typename TT=T>
ALWAYS_INLINE typename std::enable_if<!std::is_trivially_copyable<TT>::value, void>::type
uninitialized_move_n(T* __restrict first,
std::size_t count,
T* __restrict d_first)
{
for (std::size_t i=0; i < count; i++)
new (d_first++) T(std::move(*first++));
}
template <typename TT=T>
ALWAYS_INLINE typename std::enable_if<std::is_trivially_destructible<TT>::value, void>::type
destroy(T*, T*)
{ }
template <typename TT=T>
ALWAYS_INLINE typename std::enable_if<!std::is_trivially_destructible<TT>::value, void>::type
destroy(T* first, T* last)
{
while (first != last)
(--last)->~T();
}
};
template <typename T, std::size_t N>
class Array
{
public:
using value_type=T;
T array_[N];
constexpr T& operator[](std::size_t pos) noexcept
{
ASSERT(pos < size());
return array_[pos];
}
constexpr const T& operator[](std::size_t pos) const noexcept
{
ASSERT(pos < size());
return array_[pos];
}
void fill(const T& value)
{
std::fill_n(begin(), size(), value);
}
constexpr T* data() noexcept
{
return array_;
}
constexpr const T* data() const noexcept
{
return array_;
}
constexpr T* begin() noexcept
{
return array_;
}
constexpr const T* begin() const noexcept
{
return array_;
}
constexpr T* end() noexcept
{
return array_ + N;
}
constexpr const T* end() const noexcept
{
return array_ + N;
}
constexpr T& back() noexcept
{
ASSERT(N > 0);
return array_[N - 1];
}
constexpr const T& back() const noexcept
{
ASSERT(N > 0);
return array_[N - 1];
}
constexpr std::size_t size() const noexcept
{
return N;
}
};
}
#endif
#include <stdint.h>
namespace primesieve {
extern const Array<ad, 65> bitValues;
extern const Array<ad, 64> bruijnBitValues;
int get_num_threads();
int get_sieve_size();
ad get_max_stop();
ad popcount(const Vector<ad>& vect);
}
#endif
#include <stdint.h>
namespace primesieve {
const Array<ad, 65> bitValues =
{
7, 11, 13, 17, 19, 23, 29, 31,
37, 41, 43, 47, 49, 53, 59, 61,
67, 71, 73, 77, 79, 83, 89, 91,
97, 101, 103, 107, 109, 113, 119, 121,
127, 131, 133, 137, 139, 143, 149, 151,
157, 161, 163, 167, 169, 173, 179, 181,
187, 191, 193, 197, 199, 203, 209, 211,
217, 221, 223, 227, 229, 233, 239, 241,
0
};
const Array<ad, 64> bruijnBitValues =
{
7, 47, 11, 49, 67, 113, 13, 53,
89, 71, 161, 101, 119, 187, 17, 233,
59, 79, 91, 73, 133, 139, 163, 103,
149, 121, 203, 169, 191, 217, 19, 239,
43, 61, 109, 83, 157, 97, 181, 229,
77, 131, 137, 143, 199, 167, 211, 41,
107, 151, 179, 227, 127, 197, 209, 37,
173, 223, 193, 31, 221, 29, 23, 241
};
const WheelInit wheel30Init[30] =
{
{ 1, 0 }, { 0, 0 }, { 5, 1 }, { 4, 1 }, { 3, 1}, { 2, 1 }, { 1, 1 }, { 0, 1 },
{ 3, 2 }, { 2, 2 }, { 1, 2 }, { 0, 2 }, { 1, 3}, { 0, 3 }, { 3, 4 }, { 2, 4 },
{ 1, 4 }, { 0, 4 }, { 1, 5 }, { 0, 5 }, { 3, 6}, { 2, 6 }, { 1, 6 }, { 0, 6 },
{ 5, 7 }, { 4, 7 }, { 3, 7 }, { 2, 7 }, { 1, 7}, { 0, 7 }
};
const WheelInit wheel210Init[210] =
{
{ 1, 0 }, { 0, 0 }, { 9, 1 }, { 8, 1 }, { 7, 1 }, { 6, 1 }, { 5, 1 }, { 4, 1 },
{ 3, 1 }, { 2, 1 }, { 1, 1 }, { 0, 1 }, { 1, 2 }, { 0, 2 }, { 3, 3 }, { 2, 3 },
{ 1, 3 }, { 0, 3 }, { 1, 4 }, { 0, 4 }, { 3, 5 }, { 2, 5 }, { 1, 5 }, { 0, 5 },
{ 5, 6 }, { 4, 6 }, { 3, 6 }, { 2, 6 }, { 1, 6 }, { 0, 6 }, { 1, 7 }, { 0, 7 },
{ 5, 8 }, { 4, 8 }, { 3, 8 }, { 2, 8 }, { 1, 8 }, { 0, 8 }, { 3, 9 }, { 2, 9 },
{ 1, 9 }, { 0, 9 }, { 1, 10 }, { 0, 10 }, { 3, 11 }, { 2, 11 }, { 1, 11 }, { 0, 11 },
{ 5, 12 }, { 4, 12 }, { 3, 12 }, { 2, 12 }, { 1, 12 }, { 0, 12 }, { 5, 13 }, { 4, 13 },
{ 3, 13 }, { 2, 13 }, { 1, 13 }, { 0, 13 }, { 1, 14 }, { 0, 14 }, { 5, 15 }, { 4, 15 },
{ 3, 15 }, { 2, 15 }, { 1, 15 }, { 0, 15 }, { 3, 16 }, { 2, 16 }, { 1, 16 }, { 0, 16 },
{ 1, 17 }, { 0, 17 }, { 5, 18 }, { 4, 18 }, { 3, 18 }, { 2, 18 }, { 1, 18 }, { 0, 18 },
{ 3, 19 }, { 2, 19 }, { 1, 19 }, { 0, 19 }, { 5, 20 }, { 4, 20 }, { 3, 20 }, { 2, 20 },
{ 1, 20 }, { 0, 20 }, { 7, 21 }, { 6, 21 }, { 5, 21 }, { 4, 21 }, { 3, 21 }, { 2, 21 },
{ 1, 21 }, { 0, 21 }, { 3, 22 }, { 2, 22 }, { 1, 22 }, { 0, 22 }, { 1, 23 }, { 0, 23 },
{ 3, 24 }, { 2, 24 }, { 1, 24 }, { 0, 24 }, { 1, 25 }, { 0, 25 }, { 3, 26 }, { 2, 26 },
{ 1, 26 }, { 0, 26 }, { 7, 27 }, { 6, 27 }, { 5, 27 }, { 4, 27 }, { 3, 27 }, { 2, 27 },
{ 1, 27 }, { 0, 27 }, { 5, 28 }, { 4, 28 }, { 3, 28 }, { 2, 28 }, { 1, 28 }, { 0, 28 },
{ 3, 29 }, { 2, 29 }, { 1, 29 }, { 0, 29 }, { 5, 30 }, { 4, 30 }, { 3, 30 }, { 2, 30 },
{ 1, 30 }, { 0, 30 }, { 1, 31 }, { 0, 31 }, { 3, 32 }, { 2, 32 }, { 1, 32 }, { 0, 32 },
{ 5, 33 }, { 4, 33 }, { 3, 33 }, { 2, 33 }, { 1, 33 }, { 0, 33 }, { 1, 34 }, { 0, 34 },
{ 5, 35 }, { 4, 35 }, { 3, 35 }, { 2, 35 }, { 1, 35 }, { 0, 35 }, { 5, 36 }, { 4, 36 },
{ 3, 36 }, { 2, 36 }, { 1, 36 }, { 0, 36 }, { 3, 37 }, { 2, 37 }, { 1, 37 }, { 0, 37 },
{ 1, 38 }, { 0, 38 }, { 3, 39 }, { 2, 39 }, { 1, 39 }, { 0, 39 }, { 5, 40 }, { 4, 40 },
{ 3, 40 }, { 2, 40 }, { 1, 40 }, { 0, 40 }, { 1, 41 }, { 0, 41 }, { 5, 42 }, { 4, 42 },
{ 3, 42 }, { 2, 42 }, { 1, 42 }, { 0, 42 }, { 3, 43 }, { 2, 43 }, { 1, 43 }, { 0, 43 },
{ 1, 44 }, { 0, 44 }, { 3, 45 }, { 2, 45 }, { 1, 45 }, { 0, 45 }, { 1, 46 }, { 0, 46 },
{ 9, 47 }, { 8, 47 }, { 7, 47 }, { 6, 47 }, { 5, 47 }, { 4, 47 }, { 3, 47 }, { 2, 47 },
{ 1, 47 }, { 0, 47 }
};
}
#undef CHECK_FINISHED
#ifndef MEMORYPOOL_HPP
#define MEMORYPOOL_HPP
namespace primesieve {
class SievingPrime;
class Bucket;
class MemoryPool
{
public:
void resetReuse();
std::size_t ownedBytes() const;
NOINLINE void addBucket(SievingPrime*& aa);
void freeBucket(Bucket* bucket);
private:
void updateAllocCount();
void allocateBuckets();
void initBuckets(void* alignedPtr);
Bucket* stock_ = nullptr;
std::size_t count_=0;
Vector<Vector<char>> memory_;
};
}
#endif
#ifndef BUCKET_HPP
#define BUCKET_HPP
#ifndef CONFIG_HPP
#define CONFIG_HPP
#include <stdint.h>
namespace {
namespace config {
constexpr ad L1D_CACHE_BYTES=32 << 10;
constexpr ad BUCKET_BYTES=8 << 10;
constexpr ad MAX_ALLOC_BYTES=16 << 20;
constexpr ad MIN_CACHE_ITERATOR=4 << 20;
constexpr ad MAX_CACHE_ITERATOR=1 << 30;
constexpr ad MIN_THREAD_DISTANCE=(ad) 1e7;
constexpr int MAX_CACHE_LINE_SIZE=512;
constexpr double FACTOR_SIEVESIZE=33.0;
constexpr double FACTOR_ERATSMALL=0.44;
constexpr double FACTOR_ERATMEDIUM=3.0;
}
}
#endif
#ifndef PMATH_HPP
#define PMATH_HPP
#include <stdint.h>
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <limits>
#include <type_traits>
#if __cplusplus >= 202002L
#include <bit>
#endif
#if !defined(__has_builtin)
#define __has_builtin(x) 0
#endif
namespace primesieve {
template <typename X, typename Y>
X ceilDiv(X x, Y y)
{
return (X) ((x + y - 1) / y);
}
template <typename A, typename B, typename C>
B inBetween(A min, B x, C max)
{
using T=typename std::common_type<A, B, C>::type;
if ((T) x < (T) min)
return (B) min;
if ((T) x > (T) max)
return (B) max;
return x;
}
template <typename T>
constexpr bool isPow2(T x)
{
return x != 0 && (x & (x - 1)) == 0;
}
template <typename T>
constexpr T numberOfBits()
{
return (T) std::numeric_limits<
typename std::make_unsigned<T>::type
>::digits;
}
template <typename T>
T floorPow2(T x)
{
#if __cplusplus >= 202002L
if (x == 0)
return 0;
auto ux=std::make_unsigned_t<T>(x);
return ((T) 1) << (std::bit_width(ux) - 1);
#elif __has_builtin(__builtin_clzll)
if (x == 0)
return 0;
static_assert(sizeof(T) <= sizeof(unsigned long long), "Unsupported type, wider than long long!");
auto bits=numberOfBits<unsigned long long>();
T ilog2_x=(T) ((bits - 1) - __builtin_clzll(x));
return ((T) 1) << ilog2_x;
#else
for (T i=1; i < numberOfBits<T>(); i += i)
x |= (x >> i);
return x - (x >> 1);
#endif
}
template <typename T>
T ilog2(T x)
{
#if __cplusplus >= 202002L
auto ux=std::make_unsigned_t<T>(x);
ux=(ux > 0) ? ux : 1;
return std::bit_width(ux) - 1;
#elif __has_builtin(__builtin_clzll)
static_assert(sizeof(T) <= sizeof(unsigned long long), "Unsupported type, wider than long long!");
auto bits=numberOfBits<unsigned long long>();
x=(x > 0) ? x : 1;
return (T) ((bits - 1) - __builtin_clzll(x));
#else
T log2=0;
T bits=numberOfBits<T>();
for (T i=bits / 2; i > 0; i /= 2)
{
T one=1;
if (x >= (one << i))
{
x >>= i;
log2 += i;
}
}
return log2;
#endif
}
template <typename T>
T maxPrimeGap(T n)
{
double x=(double) n;
x=std::max(8.0, x);
double logx=std::log(x);
double prime_gap = logx * logx;
return (T) prime_gap;
}
#if __cplusplus >= 202002L
template <typename T>
consteval T ctSqrt(T x, T lo, T hi)
{
if (lo == hi)
return lo;
const T mid=(lo + hi + 1) / 2;
if (x / mid < mid)
return ctSqrt<T>(x, lo, mid - 1);
else
return ctSqrt(x, mid, hi);
}
template <typename T>
consteval T ctSqrt(T x)
{
return ctSqrt<T>(x, 0, x / 2 + 1);
}
#elif __cplusplus >= 201402L
template <typename T>
constexpr T ctSqrt(T x, T lo, T hi)
{
if (lo == hi)
return lo;
const T mid=(lo + hi + 1) / 2;
if (x / mid < mid)
return ctSqrt<T>(x, lo, mid - 1);
else
return ctSqrt(x, mid, hi);
}
template <typename T>
constexpr T ctSqrt(T x)
{
return ctSqrt<T>(x, 0, x / 2 + 1);
}
#else
#define MID ((lo + hi + 1) / 2)
template <typename T>
constexpr T ctSqrt(T x, T lo, T hi)
{
return lo == hi ? lo : ((x / MID < MID)
? ctSqrt<T>(x, lo, MID - 1) : ctSqrt<T>(x, MID, hi));
}
template <typename T>
constexpr T ctSqrt(T x)
{
return ctSqrt<T>(x, 0, x / 2 + 1);
}
#endif
template <typename T>
T isqrt(T x)
{
T s=(T) std::sqrt((double) x);
constexpr T sqrt_max=ctSqrt(std::numeric_limits<T>::max());
T r=std::min(s, sqrt_max);
if (r * r > x)
{
do { r--; }
while (r * r > x);
}
else if (r * 2 < x - r * r)
{
do { r++; }
while (r * 2 < x - r * r);
}
return r;
}
inline ad checkedAdd(ad x, ad y)
{
if (x >= std::numeric_limits<ad>::max() - y)
return std::numeric_limits<ad>::max();
else
return x + y;
}
inline ad checkedSub(ad x, ad y)
{
if (x > y)
return x - y;
else
return 0;
}
inline std::size_t primeCountUpper(ad start, ad stop)
{
if (start > stop)
return 0;
double x=std::max(100.0, (double) stop);
double pix=(stop - start) / (std::log(x) - 1.1) + 5;
if (pix > (double) std::numeric_limits<std::size_t>::max())
return std::numeric_limits<std::size_t>::max();
return (std::size_t) pix;
}
inline std::size_t primeCountUpper(ad stop)
{
return primeCountUpper(0, stop);
}
}
#endif
#include <stdint.h>
#include <cstddef>
namespace primesieve {
class SievingPrime
{
public:
enum {
MAX_MULTIPLEINDEX=(1 << 23) - 1,
MAX_WHEELINDEX=(1 << (32 - 23)) - 1
};
SievingPrime()=default;
SievingPrime(std::size_t aa,
std::size_t multipleIndex,
std::size_t wheelIndex)
{
set(aa, multipleIndex, wheelIndex);
}
void set(std::size_t multipleIndex,
std::size_t wheelIndex)
{
ASSERT(multipleIndex <= MAX_MULTIPLEINDEX);
ASSERT(wheelIndex <= MAX_WHEELINDEX);
indexes_=(uint32_t) (multipleIndex | (wheelIndex << 23));
}
void set(std::size_t aa,
std::size_t multipleIndex,
std::size_t wheelIndex)
{
ASSERT(multipleIndex <= MAX_MULTIPLEINDEX);
ASSERT(wheelIndex <= MAX_WHEELINDEX);
indexes_=(uint32_t) (multipleIndex | (wheelIndex << 23));
sievingPrime_=(uint32_t) aa;
}
std::size_t getSievingPrime() const
{
return sievingPrime_;
}
std::size_t getMultipleIndex() const
{
return indexes_ & MAX_MULTIPLEINDEX;
}
std::size_t getWheelIndex() const
{
return indexes_ >> 23;
}
private:
uint32_t indexes_;
uint32_t sievingPrime_;
};
class Bucket
{
public:
SievingPrime* begin() { return &sievingPrimes_[0]; }
SievingPrime* end() { return end_; }
Bucket* next() { return next_; }
void setNext(Bucket* next) { next_ = next; }
void setEnd(SievingPrime* end) { end_ = end; }
void reset() { end_=begin(); }
bool empty() { return begin() == end(); }
static Bucket* get(SievingPrime* aa)
{
ASSERT(aa != nullptr);
uintptr_t address=(uintptr_t) (void*) aa;
address -= 1;
address -= address % sizeof(Bucket);
return (Bucket*) (void*) address;
}
static bool isFull(SievingPrime* aa)
{
uintptr_t address=(uintptr_t) (void*) aa;
return address % sizeof(Bucket) == 0;
}
private:
enum {
SIEVING_PRIMES_OFFSET=sizeof(SievingPrime*) + sizeof(Bucket*),
SIEVING_PRIMES_SIZE=(config::BUCKET_BYTES - SIEVING_PRIMES_OFFSET) / sizeof(SievingPrime)
};
SievingPrime* end_;
Bucket* next_;
SievingPrime sievingPrimes_[SIEVING_PRIMES_SIZE];
};
static_assert(isPow2(sizeof(Bucket)), "sizeof(Bucket) must be a power of 2!");
}
#endif
#ifndef PRIMESIEVE_ERROR_HPP
#define PRIMESIEVE_ERROR_HPP
#include <stdexcept>
#include <string>
namespace primesieve {
class primesieve_error : public std::runtime_error
{
public:
primesieve_error(const std::string& msg)
: std::runtime_error(msg)
{ }
};
}
#endif
#include <stdint.h>
#include <algorithm>
#include <memory>
namespace primesieve {
void MemoryPool::resetReuse()
{
stock_=nullptr;
for (auto& memory : memory_)
{
std::size_t bytes=memory.size();
void* ptr = memory.data();
if (!std::align(sizeof(Bucket), sizeof(Bucket), ptr, bytes))
throw primesieve_error("MemoryPool: invalid owned chunk during reset!");
auto* buckets = static_cast<Bucket*>(ptr);
const std::size_t count=bytes / sizeof(Bucket);
for (std::size_t i=0; i < count; ++i)
{
buckets[i].reset();
buckets[i].setNext(stock_);
stock_=&buckets[i];
}
}
}
std::size_t MemoryPool::ownedBytes() const
{
std::size_t bytes=0;
for (const auto& memory : memory_) bytes += memory.capacity();
return bytes;
}
void MemoryPool::updateAllocCount()
{
std::size_t allocationNr=memory_.size() + 1;
if (allocationNr == 1)
{
count_=73;
memory_.reserve(64);
}
else if (allocationNr == 2)
{
std::size_t minBuckets=16;
count_=std::max(minBuckets, count_ / 4);
}
else
{
count_ += count_ / 8;
std::size_t maxCount=config::MAX_ALLOC_BYTES / sizeof(Bucket);
count_=std::min(count_, maxCount);
}
}
void MemoryPool::allocateBuckets()
{
updateAllocCount();
std::size_t bytes = count_ * sizeof(Bucket);
memory_.emplace_back(bytes);
void* ptr = (void*) memory_.back().data();
if_unlikely(!std::align(sizeof(Bucket), sizeof(Bucket), ptr, bytes))
throw primesieve_error("MemoryPool: failed to align memory!");
count_=bytes / sizeof(Bucket);
initBuckets(ptr);
}
void MemoryPool::initBuckets(void* alignedPtr)
{
Bucket* buckets = (Bucket*) alignedPtr;
if_unlikely(uintptr_t(buckets) % sizeof(Bucket) != 0)
throw primesieve_error("MemoryPool: failed to align memory!");
if_unlikely(count_ < 10)
throw primesieve_error("MemoryPool: insufficient buckets allocated!");
for (std::size_t i=0; i < count_; i++)
new (&buckets[i]) Bucket;
for (std::size_t i=0; i < count_ - 1; i++)
{
buckets[i].reset();
buckets[i].setNext(&buckets[i + 1]);
}
buckets[count_ - 1].reset();
buckets[count_ - 1].setNext(nullptr);
stock_=buckets;
}
void MemoryPool::addBucket(SievingPrime*& aa)
{
if (!stock_)
allocateBuckets();
Bucket* bucket = stock_;
stock_=stock_->next();
bucket->setNext(nullptr);
if (aa)
{
Bucket* old = Bucket::get(aa);
old->setEnd(aa);
bucket->setNext(old);
}
aa=bucket->begin();
}
void MemoryPool::freeBucket(Bucket* bucket)
{
bucket->reset();
bucket->setNext(stock_);
stock_=bucket;
}
}
#undef CHECK_FINISHED
#ifndef ERATSMALL_HPP
#define ERATSMALL_HPP
#include <cstddef>
#include <stdint.h>
namespace primesieve {
class EratSmall : public Wheel30_t
{
public:
void init(ad, ad, ad);
void crossOff(Vector<ad>& sieve);
bool hasSievingPrimes() const { return !primes_.empty(); }
public: 
ad maxPrime_=0;
std::size_t l1CacheSize_=0;
bool ovr_=false;
Vector<SievingPrime> primes_;
void storeSievingPrime(ad, ad, ad);
NOINLINE void crossOff(uint8_t*, std::size_t);
template<bool Ext>NOINLINE void crossOffMode(uint8_t*,std::size_t);
};
}
#endif
#ifndef BITS_HPP
#define BITS_HPP
enum
{
BIT0=0xfe,
BIT1=0xfd,
BIT2=0xfb,
BIT3=0xf7,
BIT4=0xef,
BIT5=0xdf,
BIT6=0xbf,
BIT7=0x7f
};
#endif
#include <stdint.h>
#include <algorithm>
namespace primesieve {
void EratSmall::init(ad stop,
ad l1CacheSize,
ad maxPrime)
{
ASSERT((maxPrime / 30) * getMaxFactor() + getMaxFactor() <= SievingPrime::MAX_MULTIPLEINDEX);
static_assert(config::FACTOR_ERATSMALL <= 4.5,
"config::FACTOR_ERATSMALL > 4.5 causes multipleIndex overflow 23-bits!");
stop_=stop;
maxPrime_=maxPrime;
l1CacheSize_=(std::size_t) l1CacheSize;
std::size_t count=primeCountUpper(maxPrime);
primes_.reserve(count);
}
void EratSmall::storeSievingPrime(ad prime,
ad multipleIndex,
ad wheelIndex)
{
ASSERT(prime <= maxPrime_);
ad aa=prime / 30;
primes_.emplace_back(aa, multipleIndex, wheelIndex);
}
static primesieve::SievingPrime* esSortBuf(){static SievingPrime buf[2048];return buf;}
void EratSmall::crossOff(Vector<ad>& sieve)
{
{std::size_t n=primes_.size();
if (n > 2048) n=2048;
if (n > 1)
{
SievingPrime* buf = esSortBuf();
std::size_t cnt[65];
for (int k=0;k<65;k++) cnt[k]=0;
for (std::size_t k=0;k<n;k++) cnt[primes_[k].getWheelIndex()+1]++;
for (int k=0;k<64;k++) cnt[k+1]+=cnt[k];
for (std::size_t k=0;k<n;k++){std::size_t w=primes_[k].getWheelIndex();buf[cnt[w]++]=primes_[k];}
for (std::size_t k=0;k<n;k++) primes_[k]=buf[k];
}
}
uint8_t* sieve8 = (uint8_t*) sieve.data();
std::size_t sieveBytes = g_logSieveBytes;
bool ext=ovr_;
for (std::size_t i=0; i < sieveBytes; i += l1CacheSize_)
{
std::size_t chunkSize=std::min(l1CacheSize_, sieveBytes - i);
ovr_=ext;
crossOff(&sieve8[i], chunkSize);
}
ovr_=ext;
}
void EratSmall::crossOff(uint8_t* sieve,std::size_t sieveBytes){if(ovr_)crossOffMode<true>(sieve,sieveBytes);else crossOffMode<false>(sieve,sieveBytes);}
template<bool Ext>void EratSmall::crossOffMode(uint8_t* __restrict sieve,std::size_t sieveBytes)
{
#define CHECK_FINISHED(wheelIndex) \
if (i >= sieveBytes) \
{ \
std::size_t multipleIndex=i - sieveBytes; \
prime.set(multipleIndex, wheelIndex); \
goto next_iteration; \
}
for (auto& prime : primes_)
{
std::size_t aa=prime.getSievingPrime();
std::size_t i=prime.getMultipleIndex();
std::size_t wheelIndex=prime.getWheelIndex();
ASSERT(wheelIndex <= 63);
switch (wheelIndex)
{
for (;;)
{
case 0: {
std::size_t maxOffset = aa * 28 + 6;
std::size_t limit=Ext ? sieveBytes : (std::max(sieveBytes, maxOffset) - maxOffset);
for (; i < limit; i += aa * 30 + 7)
{
sieve[i + aa * 0 + 0] &= BIT0;
sieve[i + aa * 6 + 1] &= BIT4;
sieve[i + aa * 10 + 2] &= BIT3;
sieve[i + aa * 12 + 2] &= BIT7;
sieve[i + aa * 16 + 3] &= BIT6;
sieve[i + aa * 18 + 4] &= BIT2;
sieve[i + aa * 22 + 5] &= BIT1;
sieve[i + aa * 28 + 6] &= BIT5;
}
}
ab(0); sieve[i] &= BIT0; i += aa * 6 + 1; ae;
case 1: ab(1); sieve[i] &= BIT4; i += aa * 4 + 1; ae;
case 2: ab(2); sieve[i] &= BIT3; i += aa * 2 + 0; ae;
case 3: ab(3); sieve[i] &= BIT7; i += aa * 4 + 1; ae;
case 4: ab(4); sieve[i] &= BIT6; i += aa * 2 + 1; ae;
case 5: ab(5); sieve[i] &= BIT2; i += aa * 4 + 1; ae;
case 6: ab(6); sieve[i] &= BIT1; i += aa * 6 + 1; ae;
case 7: ab(7); sieve[i] &= BIT5; i += aa * 2 + 1;
}
for (;;)
{
case 8: {
std::size_t maxOffset = aa * 28 + 10;
std::size_t limit=Ext ? sieveBytes : (std::max(sieveBytes, maxOffset) - maxOffset);
for (; i < limit; i += aa * 30 + 11)
{
sieve[i + aa * 0 + 0] &= BIT1;
sieve[i + aa * 6 + 2] &= BIT3;
sieve[i + aa * 10 + 3] &= BIT7;
sieve[i + aa * 12 + 4] &= BIT5;
sieve[i + aa * 16 + 6] &= BIT0;
sieve[i + aa * 18 + 6] &= BIT6;
sieve[i + aa * 22 + 8] &= BIT2;
sieve[i + aa * 28 + 10] &= BIT4;
}
}
ab( 8); sieve[i] &= BIT1; i += aa * 6 + 2; ae;
case 9: ab( 9); sieve[i] &= BIT3; i += aa * 4 + 1; ae;
case 10: ab(10); sieve[i] &= BIT7; i += aa * 2 + 1; ae;
case 11: ab(11); sieve[i] &= BIT5; i += aa * 4 + 2; ae;
case 12: ab(12); sieve[i] &= BIT0; i += aa * 2 + 0; ae;
case 13: ab(13); sieve[i] &= BIT6; i += aa * 4 + 2; ae;
case 14: ab(14); sieve[i] &= BIT2; i += aa * 6 + 2; ae;
case 15: ab(15); sieve[i] &= BIT4; i += aa * 2 + 1;
}
for (;;)
{
case 16: {
std::size_t maxOffset = aa * 28 + 12;
std::size_t limit=Ext ? sieveBytes : (std::max(sieveBytes, maxOffset) - maxOffset);
for (; i < limit; i += aa * 30 + 13)
{
sieve[i + aa * 0 + 0] &= BIT2;
sieve[i + aa * 6 + 2] &= BIT7;
sieve[i + aa * 10 + 4] &= BIT5;
sieve[i + aa * 12 + 5] &= BIT4;
sieve[i + aa * 16 + 7] &= BIT1;
sieve[i + aa * 18 + 8] &= BIT0;
sieve[i + aa * 22 + 9] &= BIT6;
sieve[i + aa * 28 + 12] &= BIT3;
}
}
ab(16); sieve[i] &= BIT2; i += aa * 6 + 2; ae;
case 17: ab(17); sieve[i] &= BIT7; i += aa * 4 + 2; ae;
case 18: ab(18); sieve[i] &= BIT5; i += aa * 2 + 1; ae;
case 19: ab(19); sieve[i] &= BIT4; i += aa * 4 + 2; ae;
case 20: ab(20); sieve[i] &= BIT1; i += aa * 2 + 1; ae;
case 21: ab(21); sieve[i] &= BIT0; i += aa * 4 + 1; ae;
case 22: ab(22); sieve[i] &= BIT6; i += aa * 6 + 3; ae;
case 23: ab(23); sieve[i] &= BIT3; i += aa * 2 + 1;
}
for (;;)
{
case 24: {
std::size_t maxOffset = aa * 28 + 16;
std::size_t limit=Ext ? sieveBytes : (std::max(sieveBytes, maxOffset) - maxOffset);
for (; i < limit; i += aa * 30 + 17)
{
sieve[i + aa * 0 + 0] &= BIT3;
sieve[i + aa * 6 + 3] &= BIT6;
sieve[i + aa * 10 + 6] &= BIT0;
sieve[i + aa * 12 + 7] &= BIT1;
sieve[i + aa * 16 + 9] &= BIT4;
sieve[i + aa * 18 + 10] &= BIT5;
sieve[i + aa * 22 + 12] &= BIT7;
sieve[i + aa * 28 + 16] &= BIT2;
}
}
ab(24); sieve[i] &= BIT3; i += aa * 6 + 3; ae;
case 25: ab(25); sieve[i] &= BIT6; i += aa * 4 + 3; ae;
case 26: ab(26); sieve[i] &= BIT0; i += aa * 2 + 1; ae;
case 27: ab(27); sieve[i] &= BIT1; i += aa * 4 + 2; ae;
case 28: ab(28); sieve[i] &= BIT4; i += aa * 2 + 1; ae;
case 29: ab(29); sieve[i] &= BIT5; i += aa * 4 + 2; ae;
case 30: ab(30); sieve[i] &= BIT7; i += aa * 6 + 4; ae;
case 31: ab(31); sieve[i] &= BIT2; i += aa * 2 + 1;
}
for (;;)
{
case 32: {
std::size_t maxOffset = aa * 28 + 18;
std::size_t limit=Ext ? sieveBytes : (std::max(sieveBytes, maxOffset) - maxOffset);
for (; i < limit; i += aa * 30 + 19)
{
sieve[i + aa * 0 + 0] &= BIT4;
sieve[i + aa * 6 + 4] &= BIT2;
sieve[i + aa * 10 + 6] &= BIT6;
sieve[i + aa * 12 + 8] &= BIT0;
sieve[i + aa * 16 + 10] &= BIT5;
sieve[i + aa * 18 + 11] &= BIT7;
sieve[i + aa * 22 + 14] &= BIT3;
sieve[i + aa * 28 + 18] &= BIT1;
}
}
ab(32); sieve[i] &= BIT4; i += aa * 6 + 4; ae;
case 33: ab(33); sieve[i] &= BIT2; i += aa * 4 + 2; ae;
case 34: ab(34); sieve[i] &= BIT6; i += aa * 2 + 2; ae;
case 35: ab(35); sieve[i] &= BIT0; i += aa * 4 + 2; ae;
case 36: ab(36); sieve[i] &= BIT5; i += aa * 2 + 1; ae;
case 37: ab(37); sieve[i] &= BIT7; i += aa * 4 + 3; ae;
case 38: ab(38); sieve[i] &= BIT3; i += aa * 6 + 4; ae;
case 39: ab(39); sieve[i] &= BIT1; i += aa * 2 + 1;
}
for (;;)
{
case 40: {
std::size_t maxOffset = aa * 28 + 22;
std::size_t limit=Ext ? sieveBytes : (std::max(sieveBytes, maxOffset) - maxOffset);
for (; i < limit; i += aa * 30 + 23)
{
sieve[i + aa * 0 + 0] &= BIT5;
sieve[i + aa * 6 + 5] &= BIT1;
sieve[i + aa * 10 + 8] &= BIT2;
sieve[i + aa * 12 + 9] &= BIT6;
sieve[i + aa * 16 + 12] &= BIT7;
sieve[i + aa * 18 + 14] &= BIT3;
sieve[i + aa * 22 + 17] &= BIT4;
sieve[i + aa * 28 + 22] &= BIT0;
}
}
ab(40); sieve[i] &= BIT5; i += aa * 6 + 5; ae;
case 41: ab(41); sieve[i] &= BIT1; i += aa * 4 + 3; ae;
case 42: ab(42); sieve[i] &= BIT2; i += aa * 2 + 1; ae;
case 43: ab(43); sieve[i] &= BIT6; i += aa * 4 + 3; ae;
case 44: ab(44); sieve[i] &= BIT7; i += aa * 2 + 2; ae;
case 45: ab(45); sieve[i] &= BIT3; i += aa * 4 + 3; ae;
case 46: ab(46); sieve[i] &= BIT4; i += aa * 6 + 5; ae;
case 47: ab(47); sieve[i] &= BIT0; i += aa * 2 + 1;
}
for (;;)
{
case 48: {
std::size_t maxOffset = aa * 28 + 27;
std::size_t limit=Ext ? sieveBytes : (std::max(sieveBytes, maxOffset) - maxOffset);
for (; i < limit; i += aa * 30 + 29)
{
sieve[i + aa * 0 + 0] &= BIT6;
sieve[i + aa * 6 + 6] &= BIT5;
sieve[i + aa * 10 + 10] &= BIT4;
sieve[i + aa * 12 + 12] &= BIT3;
sieve[i + aa * 16 + 16] &= BIT2;
sieve[i + aa * 18 + 18] &= BIT1;
sieve[i + aa * 22 + 22] &= BIT0;
sieve[i + aa * 28 + 27] &= BIT7;
}
}
ab(48); sieve[i] &= BIT6; i += aa * 6 + 6; ae;
case 49: ab(49); sieve[i] &= BIT5; i += aa * 4 + 4; ae;
case 50: ab(50); sieve[i] &= BIT4; i += aa * 2 + 2; ae;
case 51: ab(51); sieve[i] &= BIT3; i += aa * 4 + 4; ae;
case 52: ab(52); sieve[i] &= BIT2; i += aa * 2 + 2; ae;
case 53: ab(53); sieve[i] &= BIT1; i += aa * 4 + 4; ae;
case 54: ab(54); sieve[i] &= BIT0; i += aa * 6 + 5; ae;
case 55: ab(55); sieve[i] &= BIT7; i += aa * 2 + 2;
}
for (;;)
{
case 56: {
std::size_t maxOffset = aa * 28 + 1;
std::size_t limit=Ext ? sieveBytes : (std::max(sieveBytes, maxOffset) - maxOffset);
for (; i < limit; i += aa * 30 + 1)
{
sieve[i + aa * 0 + 0] &= BIT7;
sieve[i + aa * 6 + 1] &= BIT0;
sieve[i + aa * 10 + 1] &= BIT1;
sieve[i + aa * 12 + 1] &= BIT2;
sieve[i + aa * 16 + 1] &= BIT3;
sieve[i + aa * 18 + 1] &= BIT4;
sieve[i + aa * 22 + 1] &= BIT5;
sieve[i + aa * 28 + 1] &= BIT6;
}
}
ab(56); sieve[i] &= BIT7; i += aa * 6 + 1; ae;
case 57: ab(57); sieve[i] &= BIT0; i += aa * 4 + 0; ae;
case 58: ab(58); sieve[i] &= BIT1; i += aa * 2 + 0; ae;
case 59: ab(59); sieve[i] &= BIT2; i += aa * 4 + 0; ae;
case 60: ab(60); sieve[i] &= BIT3; i += aa * 2 + 0; ae;
case 61: ab(61); sieve[i] &= BIT4; i += aa * 4 + 0; ae;
case 62: ab(62); sieve[i] &= BIT5; i += aa * 6 + 0; ae;
case 63: ab(63); sieve[i] &= BIT6; i += aa * 2 + 0;
}
default: UNREACHABLE;
}
next_iteration:;
}
}
}
#undef CHECK_FINISHED
#ifndef ERATMEDIUM_HPP
#define ERATMEDIUM_HPP
#include <stdint.h>
namespace primesieve {
class MemoryPool;
class SievingPrime;
class Bucket;
class EratMedium : public Wheel30_t
{
public:
void init(ad, ad, MemoryPool&);
bool hasSievingPrimes() const { return !buckets_.empty(); }
NOINLINE void crossOff(Vector<ad>& sieve);
public: 
ad maxPrime_=0;
MemoryPool* memoryPool_ = nullptr;
Vector<SievingPrime*> buckets_;
Vector<SievingPrime*> currentBuckets_;
void storeSievingPrime(ad, ad, ad);
NOINLINE void crossOff_7(uint8_t*, std::size_t, Bucket*);
NOINLINE void crossOff_11(uint8_t*, std::size_t, Bucket*);
NOINLINE void crossOff_13(uint8_t*, std::size_t, Bucket*);
NOINLINE void crossOff_17(uint8_t*, std::size_t, Bucket*);
NOINLINE void crossOff_19(uint8_t*, std::size_t, Bucket*);
NOINLINE void crossOff_23(uint8_t*, std::size_t, Bucket*);
NOINLINE void crossOff_29(uint8_t*, std::size_t, Bucket*);
NOINLINE void crossOff_31(uint8_t*, std::size_t, Bucket*);
};
}
#endif
#include <stdint.h>
namespace primesieve {
void EratMedium::init(ad stop,
ad maxPrime,
MemoryPool& memoryPool)
{
ASSERT((maxPrime / 30) * getMaxFactor() + getMaxFactor() <= SievingPrime::MAX_MULTIPLEINDEX);
static_assert(config::FACTOR_ERATMEDIUM <= 4.5,
"config::FACTOR_ERATMEDIUM > 4.5 causes multipleIndex overflow 23-bits!");
stop_=stop;
maxPrime_=maxPrime;
memoryPool_=&memoryPool;
}
void EratMedium::storeSievingPrime(ad prime,
ad multipleIndex,
ad wheelIndex)
{
ASSERT(prime <= maxPrime_);
ad aa=prime / 30;
if_unlikely(buckets_.empty())
{
buckets_.resize(64);
currentBuckets_.resize(64);
std::fill_n(buckets_.begin(), 64, nullptr);
std::fill_n(currentBuckets_.begin(), 64, nullptr);
}
if (Bucket::isFull(buckets_[wheelIndex]))
memoryPool_->addBucket(buckets_[wheelIndex]);
buckets_[wheelIndex]++->set(aa, multipleIndex, wheelIndex);
}
void EratMedium::crossOff(Vector<ad>& sieve)
{
currentBuckets_.swap(buckets_);
uint8_t* sieve8 = (uint8_t*) sieve.data();
std::size_t sieveBytes = sieve.size() * sizeof(ad);
for (std::size_t i=0; i < 64; i++)
{
if (currentBuckets_[i])
{
Bucket* bucket = Bucket::get(currentBuckets_[i]);
bucket->setEnd(currentBuckets_[i]);
currentBuckets_[i]=nullptr;
std::size_t wheelIndex=i;
while (bucket)
{
switch (wheelIndex / 8)
{
case 0: crossOff_7 (sieve8, sieveBytes, bucket); break;
case 1: crossOff_11(sieve8, sieveBytes, bucket); break;
case 2: crossOff_13(sieve8, sieveBytes, bucket); break;
case 3: crossOff_17(sieve8, sieveBytes, bucket); break;
case 4: crossOff_19(sieve8, sieveBytes, bucket); break;
case 5: crossOff_23(sieve8, sieveBytes, bucket); break;
case 6: crossOff_29(sieve8, sieveBytes, bucket); break;
case 7: crossOff_31(sieve8, sieveBytes, bucket); break;
default: UNREACHABLE;
}
Bucket* processed = bucket;
bucket=bucket->next();
memoryPool_->freeBucket(processed);
}
}
}
}
#define CHECK_FINISHED(wheelIndex) \
if_unlikely(i >= sieveBytes) \
{ \
i -= sieveBytes; \
if (Bucket::isFull(buckets[wheelIndex])) \
memoryPool.addBucket(buckets[wheelIndex]); \
buckets[wheelIndex]++->set(sievingPrime, i, wheelIndex); \
break; \
}
void EratMedium::crossOff_7(uint8_t* sieve, std::size_t sieveBytes, Bucket* bucket)
{
auto buckets=buckets_.data();
MemoryPool& memoryPool=*memoryPool_;
SievingPrime* prime = bucket->begin();
SievingPrime* end = bucket->end();
std::size_t wheelIndex=prime->getWheelIndex();
for (; prime != end; prime++)
{
std::size_t aa=prime->getSievingPrime();
std::size_t i=prime->getMultipleIndex();
std::size_t dist0 = aa * 6 + 1;
std::size_t dist1 = aa * 4 + 1;
std::size_t dist2 = aa * 2 + 0;
std::size_t dist4 = aa * 2 + 1;
ASSERT(wheelIndex <= 7);
switch (wheelIndex)
{
default: UNREACHABLE;
for (;;)
{
case 0: ab(0); sieve[i] &= BIT0; i += dist0; ae;
case 1: ab(1); sieve[i] &= BIT4; i += dist1; ae;
case 2: ab(2); sieve[i] &= BIT3; i += dist2; ae;
case 3: ab(3); sieve[i] &= BIT7; i += dist1; ae;
case 4: ab(4); sieve[i] &= BIT6; i += dist4; ae;
case 5: ab(5); sieve[i] &= BIT2; i += dist1; ae;
case 6: ab(6); sieve[i] &= BIT1; i += dist0; ae;
case 7: ab(7); sieve[i] &= BIT5; i += dist4;
}
}
}
}
void EratMedium::crossOff_11(uint8_t* sieve, std::size_t sieveBytes, Bucket* bucket)
{
auto buckets=buckets_.data();
MemoryPool& memoryPool=*memoryPool_;
SievingPrime* prime = bucket->begin();
SievingPrime* end = bucket->end();
std::size_t wheelIndex=prime->getWheelIndex();
for (; prime != end; prime++)
{
std::size_t aa=prime->getSievingPrime();
std::size_t i=prime->getMultipleIndex();
std::size_t dist0 = aa * 6 + 2;
std::size_t dist1 = aa * 4 + 1;
std::size_t dist2 = aa * 2 + 1;
std::size_t dist3 = aa * 4 + 2;
std::size_t dist4 = aa * 2 + 0;
ASSERT(wheelIndex >= 8);
ASSERT(wheelIndex <= 15);
switch (wheelIndex)
{
default: UNREACHABLE;
for (;;)
{
case 8: ab( 8); sieve[i] &= BIT1; i += dist0; ae;
case 9: ab( 9); sieve[i] &= BIT3; i += dist1; ae;
case 10: ab(10); sieve[i] &= BIT7; i += dist2; ae;
case 11: ab(11); sieve[i] &= BIT5; i += dist3; ae;
case 12: ab(12); sieve[i] &= BIT0; i += dist4; ae;
case 13: ab(13); sieve[i] &= BIT6; i += dist3; ae;
case 14: ab(14); sieve[i] &= BIT2; i += dist0; ae;
case 15: ab(15); sieve[i] &= BIT4; i += dist2;
}
}
}
}
void EratMedium::crossOff_13(uint8_t* sieve, std::size_t sieveBytes, Bucket* bucket)
{
auto buckets=buckets_.data();
MemoryPool& memoryPool=*memoryPool_;
SievingPrime* prime = bucket->begin();
SievingPrime* end = bucket->end();
std::size_t wheelIndex=prime->getWheelIndex();
for (; prime != end; prime++)
{
std::size_t aa=prime->getSievingPrime();
std::size_t i=prime->getMultipleIndex();
std::size_t dist0 = aa * 6 + 2;
std::size_t dist1 = aa * 4 + 2;
std::size_t dist2 = aa * 2 + 1;
std::size_t dist5 = aa * 4 + 1;
std::size_t dist6 = aa * 6 + 3;
ASSERT(wheelIndex >= 16);
ASSERT(wheelIndex <= 23);
switch (wheelIndex)
{
default: UNREACHABLE;
for (;;)
{
case 16: ab(16); sieve[i] &= BIT2; i += dist0; ae;
case 17: ab(17); sieve[i] &= BIT7; i += dist1; ae;
case 18: ab(18); sieve[i] &= BIT5; i += dist2; ae;
case 19: ab(19); sieve[i] &= BIT4; i += dist1; ae;
case 20: ab(20); sieve[i] &= BIT1; i += dist2; ae;
case 21: ab(21); sieve[i] &= BIT0; i += dist5; ae;
case 22: ab(22); sieve[i] &= BIT6; i += dist6; ae;
case 23: ab(23); sieve[i] &= BIT3; i += dist2;
}
}
}
}
void EratMedium::crossOff_17(uint8_t* sieve, std::size_t sieveBytes, Bucket* bucket)
{
auto buckets=buckets_.data();
MemoryPool& memoryPool=*memoryPool_;
SievingPrime* prime = bucket->begin();
SievingPrime* end = bucket->end();
std::size_t wheelIndex=prime->getWheelIndex();
for (; prime != end; prime++)
{
std::size_t aa=prime->getSievingPrime();
std::size_t i=prime->getMultipleIndex();
std::size_t dist0 = aa * 6 + 3;
std::size_t dist1 = aa * 4 + 3;
std::size_t dist2 = aa * 2 + 1;
std::size_t dist3 = aa * 4 + 2;
std::size_t dist6 = aa * 6 + 4;
ASSERT(wheelIndex >= 24);
ASSERT(wheelIndex <= 31);
switch (wheelIndex)
{
default: UNREACHABLE;
for (;;)
{
case 24: ab(24); sieve[i] &= BIT3; i += dist0; ae;
case 25: ab(25); sieve[i] &= BIT6; i += dist1; ae;
case 26: ab(26); sieve[i] &= BIT0; i += dist2; ae;
case 27: ab(27); sieve[i] &= BIT1; i += dist3; ae;
case 28: ab(28); sieve[i] &= BIT4; i += dist2; ae;
case 29: ab(29); sieve[i] &= BIT5; i += dist3; ae;
case 30: ab(30); sieve[i] &= BIT7; i += dist6; ae;
case 31: ab(31); sieve[i] &= BIT2; i += dist2;
}
}
}
}
void EratMedium::crossOff_19(uint8_t* sieve, std::size_t sieveBytes, Bucket* bucket)
{
auto buckets=buckets_.data();
MemoryPool& memoryPool=*memoryPool_;
SievingPrime* prime = bucket->begin();
SievingPrime* end = bucket->end();
std::size_t wheelIndex=prime->getWheelIndex();
for (; prime != end; prime++)
{
std::size_t aa=prime->getSievingPrime();
std::size_t i=prime->getMultipleIndex();
std::size_t dist0 = aa * 6 + 4;
std::size_t dist1 = aa * 4 + 2;
std::size_t dist2 = aa * 2 + 2;
std::size_t dist4 = aa * 2 + 1;
std::size_t dist5 = aa * 4 + 3;
ASSERT(wheelIndex >= 32);
ASSERT(wheelIndex <= 39);
switch (wheelIndex)
{
default: UNREACHABLE;
for (;;)
{
case 32: ab(32); sieve[i] &= BIT4; i += dist0; ae;
case 33: ab(33); sieve[i] &= BIT2; i += dist1; ae;
case 34: ab(34); sieve[i] &= BIT6; i += dist2; ae;
case 35: ab(35); sieve[i] &= BIT0; i += dist1; ae;
case 36: ab(36); sieve[i] &= BIT5; i += dist4; ae;
case 37: ab(37); sieve[i] &= BIT7; i += dist5; ae;
case 38: ab(38); sieve[i] &= BIT3; i += dist0; ae;
case 39: ab(39); sieve[i] &= BIT1; i += dist4;
}
}
}
}
void EratMedium::crossOff_23(uint8_t* sieve, std::size_t sieveBytes, Bucket* bucket)
{
auto buckets=buckets_.data();
MemoryPool& memoryPool=*memoryPool_;
SievingPrime* prime = bucket->begin();
SievingPrime* end = bucket->end();
std::size_t wheelIndex=prime->getWheelIndex();
for (; prime != end; prime++)
{
std::size_t aa=prime->getSievingPrime();
std::size_t i=prime->getMultipleIndex();
std::size_t dist0 = aa * 6 + 5;
std::size_t dist1 = aa * 4 + 3;
std::size_t dist2 = aa * 2 + 1;
std::size_t dist4 = aa * 2 + 2;
ASSERT(wheelIndex >= 40);
ASSERT(wheelIndex <= 47);
switch (wheelIndex)
{
default: UNREACHABLE;
for (;;)
{
case 40: ab(40); sieve[i] &= BIT5; i += dist0; ae;
case 41: ab(41); sieve[i] &= BIT1; i += dist1; ae;
case 42: ab(42); sieve[i] &= BIT2; i += dist2; ae;
case 43: ab(43); sieve[i] &= BIT6; i += dist1; ae;
case 44: ab(44); sieve[i] &= BIT7; i += dist4; ae;
case 45: ab(45); sieve[i] &= BIT3; i += dist1; ae;
case 46: ab(46); sieve[i] &= BIT4; i += dist0; ae;
case 47: ab(47); sieve[i] &= BIT0; i += dist2;
}
}
}
}
void EratMedium::crossOff_29(uint8_t* sieve, std::size_t sieveBytes, Bucket* bucket)
{
auto buckets=buckets_.data();
MemoryPool& memoryPool=*memoryPool_;
SievingPrime* prime = bucket->begin();
SievingPrime* end = bucket->end();
std::size_t wheelIndex=prime->getWheelIndex();
for (; prime != end; prime++)
{
std::size_t aa=prime->getSievingPrime();
std::size_t i=prime->getMultipleIndex();
std::size_t dist0 = aa * 6 + 6;
std::size_t dist1 = aa * 4 + 4;
std::size_t dist2 = aa * 2 + 2;
std::size_t dist6 = aa * 6 + 5;
ASSERT(wheelIndex >= 48);
ASSERT(wheelIndex <= 55);
switch (wheelIndex)
{
default: UNREACHABLE;
for (;;)
{
case 48: ab(48); sieve[i] &= BIT6; i += dist0; ae;
case 49: ab(49); sieve[i] &= BIT5; i += dist1; ae;
case 50: ab(50); sieve[i] &= BIT4; i += dist2; ae;
case 51: ab(51); sieve[i] &= BIT3; i += dist1; ae;
case 52: ab(52); sieve[i] &= BIT2; i += dist2; ae;
case 53: ab(53); sieve[i] &= BIT1; i += dist1; ae;
case 54: ab(54); sieve[i] &= BIT0; i += dist6; ae;
case 55: ab(55); sieve[i] &= BIT7; i += dist2;
}
}
}
}
void EratMedium::crossOff_31(uint8_t* sieve, std::size_t sieveBytes, Bucket* bucket)
{
auto buckets=buckets_.data();
MemoryPool& memoryPool=*memoryPool_;
SievingPrime* prime = bucket->begin();
SievingPrime* end = bucket->end();
std::size_t wheelIndex=prime->getWheelIndex();
for (; prime != end; prime++)
{
std::size_t aa=prime->getSievingPrime();
std::size_t i=prime->getMultipleIndex();
std::size_t dist0 = aa * 6 + 1;
std::size_t dist1 = aa * 4 + 0;
std::size_t dist2 = aa * 2 + 0;
std::size_t dist6 = aa * 6 + 0;
ASSERT(wheelIndex >= 56);
ASSERT(wheelIndex <= 63);
switch (wheelIndex)
{
default: UNREACHABLE;
for (;;)
{
case 56: ab(56); sieve[i] &= BIT7; i += dist0; ae;
case 57: ab(57); sieve[i] &= BIT0; i += dist1; ae;
case 58: ab(58); sieve[i] &= BIT1; i += dist2; ae;
case 59: ab(59); sieve[i] &= BIT2; i += dist1; ae;
case 60: ab(60); sieve[i] &= BIT3; i += dist2; ae;
case 61: ab(61); sieve[i] &= BIT4; i += dist1; ae;
case 62: ab(62); sieve[i] &= BIT5; i += dist6; ae;
case 63: ab(63); sieve[i] &= BIT6; i += dist2;
}
}
}
}
}
#undef CHECK_FINISHED
#ifndef ERATBIG_HPP
#define ERATBIG_HPP
#include <stdint.h>
namespace primesieve {
class MemoryPool;
class SievingPrime;
class EratBig : public Wheel210_t
{
public:
void init(ad stop, ad maxPrime, const Vector<ad>& sieve, MemoryPool&);
NOINLINE void crossOff(Vector<ad>& sieve);
bool hasSievingPrimes() const { return !buckets_.empty(); }
public: 
ad remainingBytes_=ad(-1);
ad maxPrime_=0;
ad log2SieveBytes_=0;
ad moduloSieveBytes_=0;
MemoryPool* memoryPool_ = nullptr;
Vector<SievingPrime*> buckets_;
void storeSievingPrime(ad, ad, ad);
NOINLINE void crossOff(uint8_t* sieve, SievingPrime* prime, SievingPrime* end);
};
}
#endif
#include <stdint.h>
#include <algorithm>
namespace {
struct WheelElement
{
uint8_t unsetBit;
uint8_t nextMultipleFactor;
uint8_t correct;
uint32_t next;
};
static_assert(primesieve::isPow2(sizeof(WheelElement)),
"sizeof(WheelElement) must be a power of 2!");
const primesieve::Array<WheelElement, 8*48> wheel210 =
{{
{ BIT0, 10, 2, 1 }, { BIT3, 2, 0, 2 }, { BIT7, 4, 1, 3 }, { BIT6, 2, 1, 4 }, { BIT2, 4, 1, 5 }, { BIT1, 6, 1, 6 }, { BIT5, 2, 1, 7 }, { BIT0, 6, 1, 8 },
{ BIT4, 4, 1, 9 }, { BIT3, 2, 0, 10 }, { BIT7, 4, 1, 11 }, { BIT6, 6, 2, 12 }, { BIT1, 6, 1, 13 }, { BIT5, 2, 1, 14 }, { BIT0, 6, 1, 15 }, { BIT4, 4, 1, 16 },
{ BIT3, 2, 0, 17 }, { BIT7, 6, 2, 18 }, { BIT2, 4, 1, 19 }, { BIT1, 6, 1, 20 }, { BIT5, 8, 2, 21 }, { BIT4, 4, 1, 22 }, { BIT3, 2, 0, 23 }, { BIT7, 4, 1, 24 },
{ BIT6, 2, 1, 25 }, { BIT2, 4, 1, 26 }, { BIT1, 8, 2, 27 }, { BIT0, 6, 1, 28 }, { BIT4, 4, 1, 29 }, { BIT3, 6, 1, 30 }, { BIT6, 2, 1, 31 }, { BIT2, 4, 1, 32 },
{ BIT1, 6, 1, 33 }, { BIT5, 2, 1, 34 }, { BIT0, 6, 1, 35 }, { BIT4, 6, 1, 36 }, { BIT7, 4, 1, 37 }, { BIT6, 2, 1, 38 }, { BIT2, 4, 1, 39 }, { BIT1, 6, 1, 40 },
{ BIT5, 2, 1, 41 }, { BIT0, 6, 1, 42 }, { BIT4, 4, 1, 43 }, { BIT3, 2, 0, 44 }, { BIT7, 4, 1, 45 }, { BIT6, 2, 1, 46 }, { BIT2, 10, 2, 47 }, { BIT5, 2, 1, 0 },
{ BIT1, 10, 3, 49 }, { BIT7, 2, 1, 50 }, { BIT5, 4, 2, 51 }, { BIT0, 2, 0, 52 }, { BIT6, 4, 2, 53 }, { BIT2, 6, 2, 54 }, { BIT4, 2, 1, 55 }, { BIT1, 6, 2, 56 },
{ BIT3, 4, 1, 57 }, { BIT7, 2, 1, 58 }, { BIT5, 4, 2, 59 }, { BIT0, 6, 2, 60 }, { BIT2, 6, 2, 61 }, { BIT4, 2, 1, 62 }, { BIT1, 6, 2, 63 }, { BIT3, 4, 1, 64 },
{ BIT7, 2, 1, 65 }, { BIT5, 6, 2, 66 }, { BIT6, 4, 2, 67 }, { BIT2, 6, 2, 68 }, { BIT4, 8, 3, 69 }, { BIT3, 4, 1, 70 }, { BIT7, 2, 1, 71 }, { BIT5, 4, 2, 72 },
{ BIT0, 2, 0, 73 }, { BIT6, 4, 2, 74 }, { BIT2, 8, 3, 75 }, { BIT1, 6, 2, 76 }, { BIT3, 4, 1, 77 }, { BIT7, 6, 3, 78 }, { BIT0, 2, 0, 79 }, { BIT6, 4, 2, 80 },
{ BIT2, 6, 2, 81 }, { BIT4, 2, 1, 82 }, { BIT1, 6, 2, 83 }, { BIT3, 6, 2, 84 }, { BIT5, 4, 2, 85 }, { BIT0, 2, 0, 86 }, { BIT6, 4, 2, 87 }, { BIT2, 6, 2, 88 },
{ BIT4, 2, 1, 89 }, { BIT1, 6, 2, 90 }, { BIT3, 4, 1, 91 }, { BIT7, 2, 1, 92 }, { BIT5, 4, 2, 93 }, { BIT0, 2, 0, 94 }, { BIT6, 10, 4, 95 }, { BIT4, 2, 1, 48 },
{ BIT2, 10, 4, 97 }, { BIT5, 2, 1, 98 }, { BIT4, 4, 2, 99 }, { BIT1, 2, 1, 100 }, { BIT0, 4, 1, 101 }, { BIT6, 6, 3, 102 }, { BIT3, 2, 1, 103 }, { BIT2, 6, 2, 104 },
{ BIT7, 4, 2, 105 }, { BIT5, 2, 1, 106 }, { BIT4, 4, 2, 107 }, { BIT1, 6, 2, 108 }, { BIT6, 6, 3, 109 }, { BIT3, 2, 1, 110 }, { BIT2, 6, 2, 111 }, { BIT7, 4, 2, 112 },
{ BIT5, 2, 1, 113 }, { BIT4, 6, 3, 114 }, { BIT0, 4, 1, 115 }, { BIT6, 6, 3, 116 }, { BIT3, 8, 3, 117 }, { BIT7, 4, 2, 118 }, { BIT5, 2, 1, 119 }, { BIT4, 4, 2, 120 },
{ BIT1, 2, 1, 121 }, { BIT0, 4, 1, 122 }, { BIT6, 8, 4, 123 }, { BIT2, 6, 2, 124 }, { BIT7, 4, 2, 125 }, { BIT5, 6, 3, 126 }, { BIT1, 2, 1, 127 }, { BIT0, 4, 1, 128 },
{ BIT6, 6, 3, 129 }, { BIT3, 2, 1, 130 }, { BIT2, 6, 2, 131 }, { BIT7, 6, 3, 132 }, { BIT4, 4, 2, 133 }, { BIT1, 2, 1, 134 }, { BIT0, 4, 1, 135 }, { BIT6, 6, 3, 136 },
{ BIT3, 2, 1, 137 }, { BIT2, 6, 2, 138 }, { BIT7, 4, 2, 139 }, { BIT5, 2, 1, 140 }, { BIT4, 4, 2, 141 }, { BIT1, 2, 1, 142 }, { BIT0, 10, 4, 143 }, { BIT3, 2, 1, 96 },
{ BIT3, 10, 6, 145 }, { BIT0, 2, 1, 146 }, { BIT1, 4, 2, 147 }, { BIT4, 2, 1, 148 }, { BIT5, 4, 2, 149 }, { BIT7, 6, 4, 150 }, { BIT2, 2, 1, 151 }, { BIT3, 6, 3, 152 },
{ BIT6, 4, 3, 153 }, { BIT0, 2, 1, 154 }, { BIT1, 4, 2, 155 }, { BIT4, 6, 3, 156 }, { BIT7, 6, 4, 157 }, { BIT2, 2, 1, 158 }, { BIT3, 6, 3, 159 }, { BIT6, 4, 3, 160 },
{ BIT0, 2, 1, 161 }, { BIT1, 6, 3, 162 }, { BIT5, 4, 2, 163 }, { BIT7, 6, 4, 164 }, { BIT2, 8, 4, 165 }, { BIT6, 4, 3, 166 }, { BIT0, 2, 1, 167 }, { BIT1, 4, 2, 168 },
{ BIT4, 2, 1, 169 }, { BIT5, 4, 2, 170 }, { BIT7, 8, 5, 171 }, { BIT3, 6, 3, 172 }, { BIT6, 4, 3, 173 }, { BIT0, 6, 3, 174 }, { BIT4, 2, 1, 175 }, { BIT5, 4, 2, 176 },
{ BIT7, 6, 4, 177 }, { BIT2, 2, 1, 178 }, { BIT3, 6, 3, 179 }, { BIT6, 6, 4, 180 }, { BIT1, 4, 2, 181 }, { BIT4, 2, 1, 182 }, { BIT5, 4, 2, 183 }, { BIT7, 6, 4, 184 },
{ BIT2, 2, 1, 185 }, { BIT3, 6, 3, 186 }, { BIT6, 4, 3, 187 }, { BIT0, 2, 1, 188 }, { BIT1, 4, 2, 189 }, { BIT4, 2, 1, 190 }, { BIT5, 10, 6, 191 }, { BIT2, 2, 1, 144 },
{ BIT4, 10, 6, 193 }, { BIT6, 2, 2, 194 }, { BIT0, 4, 2, 195 }, { BIT5, 2, 1, 196 }, { BIT7, 4, 3, 197 }, { BIT3, 6, 4, 198 }, { BIT1, 2, 1, 199 }, { BIT4, 6, 4, 200 },
{ BIT2, 4, 2, 201 }, { BIT6, 2, 2, 202 }, { BIT0, 4, 2, 203 }, { BIT5, 6, 4, 204 }, { BIT3, 6, 4, 205 }, { BIT1, 2, 1, 206 }, { BIT4, 6, 4, 207 }, { BIT2, 4, 2, 208 },
{ BIT6, 2, 2, 209 }, { BIT0, 6, 3, 210 }, { BIT7, 4, 3, 211 }, { BIT3, 6, 4, 212 }, { BIT1, 8, 5, 213 }, { BIT2, 4, 2, 214 }, { BIT6, 2, 2, 215 }, { BIT0, 4, 2, 216 },
{ BIT5, 2, 1, 217 }, { BIT7, 4, 3, 218 }, { BIT3, 8, 5, 219 }, { BIT4, 6, 4, 220 }, { BIT2, 4, 2, 221 }, { BIT6, 6, 4, 222 }, { BIT5, 2, 1, 223 }, { BIT7, 4, 3, 224 },
{ BIT3, 6, 4, 225 }, { BIT1, 2, 1, 226 }, { BIT4, 6, 4, 227 }, { BIT2, 6, 4, 228 }, { BIT0, 4, 2, 229 }, { BIT5, 2, 1, 230 }, { BIT7, 4, 3, 231 }, { BIT3, 6, 4, 232 },
{ BIT1, 2, 1, 233 }, { BIT4, 6, 4, 234 }, { BIT2, 4, 2, 235 }, { BIT6, 2, 2, 236 }, { BIT0, 4, 2, 237 }, { BIT5, 2, 1, 238 }, { BIT7, 10, 7, 239 }, { BIT1, 2, 1, 192 },
{ BIT5, 10, 8, 241 }, { BIT2, 2, 1, 242 }, { BIT6, 4, 3, 243 }, { BIT7, 2, 2, 244 }, { BIT3, 4, 3, 245 }, { BIT4, 6, 5, 246 }, { BIT0, 2, 1, 247 }, { BIT5, 6, 5, 248 },
{ BIT1, 4, 3, 249 }, { BIT2, 2, 1, 250 }, { BIT6, 4, 3, 251 }, { BIT7, 6, 5, 252 }, { BIT4, 6, 5, 253 }, { BIT0, 2, 1, 254 }, { BIT5, 6, 5, 255 }, { BIT1, 4, 3, 256 },
{ BIT2, 2, 1, 257 }, { BIT6, 6, 5, 258 }, { BIT3, 4, 3, 259 }, { BIT4, 6, 5, 260 }, { BIT0, 8, 6, 261 }, { BIT1, 4, 3, 262 }, { BIT2, 2, 1, 263 }, { BIT6, 4, 3, 264 },
{ BIT7, 2, 2, 265 }, { BIT3, 4, 3, 266 }, { BIT4, 8, 6, 267 }, { BIT5, 6, 5, 268 }, { BIT1, 4, 3, 269 }, { BIT2, 6, 4, 270 }, { BIT7, 2, 2, 271 }, { BIT3, 4, 3, 272 },
{ BIT4, 6, 5, 273 }, { BIT0, 2, 1, 274 }, { BIT5, 6, 5, 275 }, { BIT1, 6, 4, 276 }, { BIT6, 4, 3, 277 }, { BIT7, 2, 2, 278 }, { BIT3, 4, 3, 279 }, { BIT4, 6, 5, 280 },
{ BIT0, 2, 1, 281 }, { BIT5, 6, 5, 282 }, { BIT1, 4, 3, 283 }, { BIT2, 2, 1, 284 }, { BIT6, 4, 3, 285 }, { BIT7, 2, 2, 286 }, { BIT3, 10, 8, 287 }, { BIT0, 2, 1, 240 },
{ BIT6, 10, 10, 289 }, { BIT4, 2, 2, 290 }, { BIT3, 4, 4, 291 }, { BIT2, 2, 2, 292 }, { BIT1, 4, 4, 293 }, { BIT0, 6, 5, 294 }, { BIT7, 2, 2, 295 }, { BIT6, 6, 6, 296 },
{ BIT5, 4, 4, 297 }, { BIT4, 2, 2, 298 }, { BIT3, 4, 4, 299 }, { BIT2, 6, 6, 300 }, { BIT0, 6, 5, 301 }, { BIT7, 2, 2, 302 }, { BIT6, 6, 6, 303 }, { BIT5, 4, 4, 304 },
{ BIT4, 2, 2, 305 }, { BIT3, 6, 6, 306 }, { BIT1, 4, 4, 307 }, { BIT0, 6, 5, 308 }, { BIT7, 8, 8, 309 }, { BIT5, 4, 4, 310 }, { BIT4, 2, 2, 311 }, { BIT3, 4, 4, 312 },
{ BIT2, 2, 2, 313 }, { BIT1, 4, 4, 314 }, { BIT0, 8, 7, 315 }, { BIT6, 6, 6, 316 }, { BIT5, 4, 4, 317 }, { BIT4, 6, 6, 318 }, { BIT2, 2, 2, 319 }, { BIT1, 4, 4, 320 },
{ BIT0, 6, 5, 321 }, { BIT7, 2, 2, 322 }, { BIT6, 6, 6, 323 }, { BIT5, 6, 6, 324 }, { BIT3, 4, 4, 325 }, { BIT2, 2, 2, 326 }, { BIT1, 4, 4, 327 }, { BIT0, 6, 5, 328 },
{ BIT7, 2, 2, 329 }, { BIT6, 6, 6, 330 }, { BIT5, 4, 4, 331 }, { BIT4, 2, 2, 332 }, { BIT3, 4, 4, 333 }, { BIT2, 2, 2, 334 }, { BIT1, 10, 9, 335 }, { BIT7, 2, 2, 288 },
{ BIT7, 10, 1, 337 }, { BIT1, 2, 0, 338 }, { BIT2, 4, 0, 339 }, { BIT3, 2, 0, 340 }, { BIT4, 4, 0, 341 }, { BIT5, 6, 0, 342 }, { BIT6, 2, 0, 343 }, { BIT7, 6, 1, 344 },
{ BIT0, 4, 0, 345 }, { BIT1, 2, 0, 346 }, { BIT2, 4, 0, 347 }, { BIT3, 6, 0, 348 }, { BIT5, 6, 0, 349 }, { BIT6, 2, 0, 350 }, { BIT7, 6, 1, 351 }, { BIT0, 4, 0, 352 },
{ BIT1, 2, 0, 353 }, { BIT2, 6, 0, 354 }, { BIT4, 4, 0, 355 }, { BIT5, 6, 0, 356 }, { BIT6, 8, 1, 357 }, { BIT0, 4, 0, 358 }, { BIT1, 2, 0, 359 }, { BIT2, 4, 0, 360 },
{ BIT3, 2, 0, 361 }, { BIT4, 4, 0, 362 }, { BIT5, 8, 0, 363 }, { BIT7, 6, 1, 364 }, { BIT0, 4, 0, 365 }, { BIT1, 6, 0, 366 }, { BIT3, 2, 0, 367 }, { BIT4, 4, 0, 368 },
{ BIT5, 6, 0, 369 }, { BIT6, 2, 0, 370 }, { BIT7, 6, 1, 371 }, { BIT0, 6, 0, 372 }, { BIT2, 4, 0, 373 }, { BIT3, 2, 0, 374 }, { BIT4, 4, 0, 375 }, { BIT5, 6, 0, 376 },
{ BIT6, 2, 0, 377 }, { BIT7, 6, 1, 378 }, { BIT0, 4, 0, 379 }, { BIT1, 2, 0, 380 }, { BIT2, 4, 0, 381 }, { BIT3, 2, 0, 382 }, { BIT4, 10, 0, 383 }, { BIT6, 2, 0, 336 }
}};
}
namespace primesieve {
void EratBig::init(ad stop,
ad maxPrime,
const Vector<ad>& sieve,
MemoryPool& memoryPool)
{
ad sieveBytes = sieve.size() * sizeof(ad);
ASSERT(isPow2(sieveBytes));
ASSERT(sieveBytes <= SievingPrime::MAX_MULTIPLEINDEX + 1);
stop_=stop;
maxPrime_=maxPrime;
log2SieveBytes_=ilog2(sieveBytes);
moduloSieveBytes_=sieveBytes - 1;
memoryPool_=&memoryPool;
ad maxSievingPrime=maxPrime_ / 30;
ad maxNextMultiple = maxSievingPrime * getMaxFactor() + getMaxFactor();
ad maxMultipleIndex=sieveBytes - 1 + maxNextMultiple;
ad maxSegmentIndex=maxMultipleIndex >> log2SieveBytes_;
ad maxSize=maxSegmentIndex + 1;
buckets_.reserve(maxSize);
}
void EratBig::storeSievingPrime(ad prime,
ad multipleIndex,
ad wheelIndex)
{
ad sieveBytes=1ull << log2SieveBytes_;
ad aa=prime / 30;
ad maxNextMultiple = aa * getMaxFactor() + getMaxFactor();
ad maxMultipleIndex=sieveBytes - 1 + maxNextMultiple;
ad maxSegmentIndex=maxMultipleIndex >> log2SieveBytes_;
ad newSize=maxSegmentIndex + 1;
ad segment=multipleIndex >> log2SieveBytes_;
multipleIndex &= moduloSieveBytes_;
while (buckets_.size() < newSize)
buckets_.push_back(nullptr);
ASSERT(prime <= maxPrime_);
ASSERT(segment < buckets_.size());
if (Bucket::isFull(buckets_[segment]))
memoryPool_->addBucket(buckets_[segment]);
buckets_[segment]++->set(aa, multipleIndex, wheelIndex);
}
void EratBig::crossOff(Vector<ad>& sieve)
{
uint8_t* sieve8 = (uint8_t*) sieve.data();
while (buckets_[0])
{
Bucket* bucket = Bucket::get(buckets_[0]);
bucket->setEnd(buckets_[0]);
buckets_[0]=nullptr;
while (bucket)
{
crossOff(sieve8, bucket->begin(), bucket->end());
Bucket* processed = bucket;
bucket=bucket->next();
memoryPool_->freeBucket(processed);
}
}
auto* bucket = buckets_[0];
std::copy(buckets_.begin() + 1, buckets_.end(), buckets_.begin());
buckets_.back()=bucket;
if (remainingBytes_ != ad(-1))
{
const ad bytes=ad(1) << log2SieveBytes_;
remainingBytes_=remainingBytes_ > bytes ? remainingBytes_ - bytes : 0;
}
}
void EratBig::crossOff(uint8_t* sieve,
SievingPrime* prime,
SievingPrime* end)
{
auto buckets=buckets_.data();
MemoryPool& memoryPool=*memoryPool_;
std::size_t moduloSieveBytes=moduloSieveBytes_;
std::size_t log2SieveBytes=log2SieveBytes_;
for (; prime != end; prime++)
{
std::size_t multipleIndex=prime->getMultipleIndex();
std::size_t wheelIndex=prime->getWheelIndex();
std::size_t aa=prime->getSievingPrime();
sieve[multipleIndex] &= wheel210[wheelIndex].unsetBit;
multipleIndex += wheel210[wheelIndex].nextMultipleFactor * aa;
multipleIndex += wheel210[wheelIndex].correct;
wheelIndex=wheel210[wheelIndex].next;
if (multipleIndex >= remainingBytes_) continue;
std::size_t segment=multipleIndex >> log2SieveBytes;
multipleIndex &= moduloSieveBytes;
if (Bucket::isFull(buckets[segment]))
memoryPool.addBucket(buckets[segment]);
buckets[segment]++->set(aa, multipleIndex, wheelIndex);
}
}
}
#undef CHECK_FINISHED
#ifndef PRESIEVE_HPP
#define PRESIEVE_HPP
#include <stdint.h>
namespace primesieve {
class PreSieve
{
public:
static void preSieve(Vector<ad>& sieve, unsigned __int128 segmentLow);
static ad getMaxPrime() { return 199; }
};
}
#endif
namespace {
const primesieve::Array<size_t,20> preSieveTableSizes={5957,6479,6409,8159,8471,9071,10123,10679,10919,11591,11857,11899,12403,12533,13261,13483,13837,13493,13589,12317};
static constexpr unsigned root_ps[20][3]={{7,23,37},{11,19,31},{13,17,29},{41,199,0},{43,197,0},{47,193,0},{53,191,0},{59,181,0},{61,179,0},{67,173,0},{71,167,0},{73,163,0},{79,157,0},{83,151,0},{89,149,0},{97,139,0},{101,137,0},{103,131,0},{107,127,0},{109,113,0}};
static constexpr size_t root_sizes[20]={5957,6479,6409,8159,8471,9071,10123,10679,10919,11591,11857,11899,12403,12533,13261,13483,13837,13493,13589,12317};
template<unsigned T>struct RootPreTable{uint8_t a[root_sizes[T]+1023]{};constexpr RootPreTable(){for(auto&x:a)x=255;const unsigned off[8]={7,11,13,17,19,23,29,31};for(unsigned p:root_ps[T])if(p){unsigned inv=1;while((30*inv)%p!=1)++inv;for(unsigned b=0;b<8;b++){unsigned start=((p-off[b]%p)*inv)%p;for(size_t j=start;j<root_sizes[T]+1023;j+=p)a[j]&=~(1u<<b);}}}};
static constexpr RootPreTable<0> root_pre_0{};
static constexpr RootPreTable<1> root_pre_1{};
static constexpr RootPreTable<2> root_pre_2{};
static constexpr RootPreTable<3> root_pre_3{};
static constexpr RootPreTable<4> root_pre_4{};
static constexpr RootPreTable<5> root_pre_5{};
static constexpr RootPreTable<6> root_pre_6{};
static constexpr RootPreTable<7> root_pre_7{};
static constexpr RootPreTable<8> root_pre_8{};
static constexpr RootPreTable<9> root_pre_9{};
static constexpr RootPreTable<10> root_pre_10{};
static constexpr RootPreTable<11> root_pre_11{};
static constexpr RootPreTable<12> root_pre_12{};
static constexpr RootPreTable<13> root_pre_13{};
static constexpr RootPreTable<14> root_pre_14{};
static constexpr RootPreTable<15> root_pre_15{};
static constexpr RootPreTable<16> root_pre_16{};
static constexpr RootPreTable<17> root_pre_17{};
static constexpr RootPreTable<18> root_pre_18{};
static constexpr RootPreTable<19> root_pre_19{};
const primesieve::Array<const uint8_t*,20> preSieveTables={root_pre_0.a,root_pre_1.a,root_pre_2.a,root_pre_3.a,root_pre_4.a,root_pre_5.a,root_pre_6.a,root_pre_7.a,root_pre_8.a,root_pre_9.a,root_pre_10.a,root_pre_11.a,root_pre_12.a,root_pre_13.a,root_pre_14.a,root_pre_15.a,root_pre_16.a,root_pre_17.a,root_pre_18.a,root_pre_19.a};
}
#ifndef CPU_ARCH_MACROS_HPP
#define CPU_ARCH_MACROS_HPP
#if defined(ENABLE_MULTIARCH_AVX2)
#define ENABLE_MULTIARCH_AVX2_BMI2
#endif
#if defined(__AVX512F__) && \
defined(__AVX512VBMI__) && \
defined(__AVX512VBMI2__) && \
defined(__POPCNT__) && \
!defined(__i386__) && \
__has_include(<immintrin.h>)
#define ENABLE_AVX512_VBMI2
#undef ENABLE_MULTIARCH_AVX512_VBMI2
#undef ENABLE_MULTIARCH_AVX2_BMI2
#elif defined(__AVX2__) && \
defined(__BMI2__) && \
defined(__POPCNT__) && \
!defined(__i386__) && \
__has_include(<immintrin.h>)
#define ENABLE_AVX2_BMI2
#undef ENABLE_MULTIARCH_AVX2_BMI2
#elif defined(__AVX2__) && \
defined(_MSC_VER) && \
!defined(_M_IX86) && \
__has_include(<immintrin.h>)
#define ENABLE_AVX2_BMI2
#undef ENABLE_MULTIARCH_AVX2_BMI2
#endif
#if defined(__AVX512F__) && \
defined(__AVX512BW__) && \
__has_include(<immintrin.h>)
#define ENABLE_AVX512_BW
#undef ENABLE_MULTIARCH_AVX512_BW
#undef ENABLE_MULTIARCH_AVX2
#elif defined(__AVX2__) && \
__has_include(<immintrin.h>)
#define ENABLE_AVX2
#undef ENABLE_MULTIARCH_AVX2
#elif (defined(__SSE2__) || \
defined(_M_X64)) && \
__has_include(<emmintrin.h>)
#define ENABLE_SSE2
#elif defined(__ARM_FEATURE_SVE) && \
__has_include(<arm_sve.h>)
#define ENABLE_ARM_SVE
#undef ENABLE_MULTIARCH_ARM_SVE
#endif
#if (defined(__aarch64__) || \
defined(_M_ARM64)) && \
__has_include(<arm_neon.h>)
#define ENABLE_ARM_NEON
#endif
#endif
#include <stdint.h>
#include <algorithm>
#include <cstddef>
#include <utility>
#define PRESIEVE1_DEFAULT presieve1_x86_avx2
#define PRESIEVE2_DEFAULT presieve2_x86_avx2
#ifndef PRESIEVE_X86_AVX2_HPP
#define PRESIEVE_X86_AVX2_HPP
#include <immintrin.h>
#include <x86intrin.h>
#include <stdint.h>
#include <cstddef>
namespace {
#if defined(ENABLE_MULTIARCH_AVX2)
PRIMESIEVE_TARGET_ATTRIBUTE("avx2")
#endif
namespace {
static inline __m256i ps_ld32(const void*p){__m256i v;__asm__("vmovdqu %1,%0":"=x"(v):"m"(*(const unsigned char(*)[32])p));return v;}
static inline void ps_st32(void*p,__m256i v){__asm__ volatile("vmovdqu %1,%0":"=m"(*(unsigned char(*)[32])p):"x"(v):"memory");}
}
void presieve1_x86_avx2(const uint8_t* __restrict preSieved0,
const uint8_t* __restrict preSieved1,
const uint8_t* __restrict preSieved2,
const uint8_t* __restrict preSieved3,
uint8_t* __restrict sieve,
std::size_t bytes)
{
std::size_t i=0;
std::size_t limit=bytes - bytes % sizeof(__m256i);
NO_UNROLL_LOOP
for (; i < limit; i += sizeof(__m256i))
{
ps_st32(&sieve[i],
_mm256_and_si256(
_mm256_and_si256(ps_ld32(&preSieved0[i]), ps_ld32(&preSieved1[i])),
_mm256_and_si256(ps_ld32(&preSieved2[i]), ps_ld32(&preSieved3[i]))));
}
NO_UNROLL_LOOP
NO_VECTORIZE_LOOP
for (; i < bytes; i++)
sieve[i]=preSieved0[i] & preSieved1[i] & preSieved2[i] & preSieved3[i];
}
#if defined(ENABLE_MULTIARCH_AVX2)
PRIMESIEVE_TARGET_ATTRIBUTE("avx2")
#endif
void presieve2_x86_avx2(const uint8_t* __restrict preSieved0,
const uint8_t* __restrict preSieved1,
const uint8_t* __restrict preSieved2,
const uint8_t* __restrict preSieved3,
uint8_t* __restrict sieve,
std::size_t bytes)
{
std::size_t i=0;
std::size_t limit=bytes - bytes % sizeof(__m256i);
NO_UNROLL_LOOP
for (; i < limit; i += sizeof(__m256i))
{
ps_st32(&sieve[i],
_mm256_and_si256(ps_ld32(&sieve[i]), _mm256_and_si256(
_mm256_and_si256(ps_ld32(&preSieved0[i]), ps_ld32(&preSieved1[i])),
_mm256_and_si256(ps_ld32(&preSieved2[i]), ps_ld32(&preSieved3[i])))));
}
NO_UNROLL_LOOP
NO_VECTORIZE_LOOP
for (; i < bytes; i++)
sieve[i] &= preSieved0[i] & preSieved1[i] & preSieved2[i] & preSieved3[i];
}
}
#endif
namespace {
template <typename... Args>
void presieve1(Args&&... args)
{
#if defined(ENABLE_MULTIARCH_AVX512_BW)
if (cpu_supports_avx512_bw)
return presieve1_x86_avx512(std::forward<Args>(args)...);
#endif
#if defined(ENABLE_MULTIARCH_AVX2)
if (cpu_supports_avx2)
return presieve1_x86_avx2(std::forward<Args>(args)...);
#endif
#if defined(ENABLE_MULTIARCH_ARM_SVE)
if (cpu_supports_sve)
return presieve1_arm_sve(std::forward<Args>(args)...);
#endif
PRESIEVE1_DEFAULT(std::forward<Args>(args)...);
}
template <typename... Args>
void presieve2(Args&&... args)
{
#if defined(ENABLE_MULTIARCH_AVX512_BW)
if (cpu_supports_avx512_bw)
return presieve2_x86_avx512(std::forward<Args>(args)...);
#endif
#if defined(ENABLE_MULTIARCH_AVX2)
if (cpu_supports_avx2)
return presieve2_x86_avx2(std::forward<Args>(args)...);
#endif
#if defined(ENABLE_MULTIARCH_ARM_SVE)
if (cpu_supports_sve)
return presieve2_arm_sve(std::forward<Args>(args)...);
#endif
PRESIEVE2_DEFAULT(std::forward<Args>(args)...);
}
}
namespace primesieve {
namespace {
static void ps1_big(const uint8_t* const* p,uint8_t* __restrict out,std::size_t bytes){
std::size_t i=0;
for(;i+64<=bytes;i+=64){__m256i v0;__m256i v1;asm("vmovdqu %[a0],%[v0]; vmovdqu %[a1],%[v1]; vpand %[b0],%[v0],%[v0]; vpand %[b1],%[v1],%[v1]; vpand %[c0],%[v0],%[v0]; vpand %[c1],%[v1],%[v1]; vpand %[d0],%[v0],%[v0]; vpand %[d1],%[v1],%[v1]; vpand %[e0],%[v0],%[v0]; vpand %[e1],%[v1],%[v1]; vpand %[f0],%[v0],%[v0]; vpand %[f1],%[v1],%[v1]; vpand %[g0],%[v0],%[v0]; vpand %[g1],%[v1],%[v1]; vpand %[h0],%[v0],%[v0]; vpand %[h1],%[v1],%[v1]; vpand %[i0],%[v0],%[v0]; vpand %[i1],%[v1],%[v1]; vpand %[j0],%[v0],%[v0]; vpand %[j1],%[v1],%[v1]; vmovdqu %[v0],%[o0]; vmovdqu %[v1],%[o1]; ":[v0]"=&x"(v0),[o0]"=m"(*(unsigned char(*)[32])(out+i+0)),[v1]"=&x"(v1),[o1]"=m"(*(unsigned char(*)[32])(out+i+32)):[a0]"m"(*(const unsigned char(*)[32])(p[0]+i+0)),[a1]"m"(*(const unsigned char(*)[32])(p[0]+i+32)),[b0]"m"(*(const unsigned char(*)[32])(p[1]+i+0)),[b1]"m"(*(const unsigned char(*)[32])(p[1]+i+32)),[c0]"m"(*(const unsigned char(*)[32])(p[2]+i+0)),[c1]"m"(*(const unsigned char(*)[32])(p[2]+i+32)),[d0]"m"(*(const unsigned char(*)[32])(p[3]+i+0)),[d1]"m"(*(const unsigned char(*)[32])(p[3]+i+32)),[e0]"m"(*(const unsigned char(*)[32])(p[4]+i+0)),[e1]"m"(*(const unsigned char(*)[32])(p[4]+i+32)),[f0]"m"(*(const unsigned char(*)[32])(p[5]+i+0)),[f1]"m"(*(const unsigned char(*)[32])(p[5]+i+32)),[g0]"m"(*(const unsigned char(*)[32])(p[6]+i+0)),[g1]"m"(*(const unsigned char(*)[32])(p[6]+i+32)),[h0]"m"(*(const unsigned char(*)[32])(p[7]+i+0)),[h1]"m"(*(const unsigned char(*)[32])(p[7]+i+32)),[i0]"m"(*(const unsigned char(*)[32])(p[8]+i+0)),[i1]"m"(*(const unsigned char(*)[32])(p[8]+i+32)),[j0]"m"(*(const unsigned char(*)[32])(p[9]+i+0)),[j1]"m"(*(const unsigned char(*)[32])(p[9]+i+32)));}
for(;i<bytes;++i)out[i]=p[0][i]&p[1][i]&p[2][i]&p[3][i]&p[4][i]&p[5][i]&p[6][i]&p[7][i]&p[8][i]&p[9][i];
}
static void ps2_big(const uint8_t* const* p,uint8_t* __restrict out,std::size_t bytes){
std::size_t i=0;
for(;i+64<=bytes;i+=64){__m256i v0;__m256i v1;asm("vmovdqu %[o0],%[v0]; vmovdqu %[o1],%[v1]; vpand %[a0],%[v0],%[v0]; vpand %[a1],%[v1],%[v1]; vpand %[b0],%[v0],%[v0]; vpand %[b1],%[v1],%[v1]; vpand %[c0],%[v0],%[v0]; vpand %[c1],%[v1],%[v1]; vpand %[d0],%[v0],%[v0]; vpand %[d1],%[v1],%[v1]; vpand %[e0],%[v0],%[v0]; vpand %[e1],%[v1],%[v1]; vpand %[f0],%[v0],%[v0]; vpand %[f1],%[v1],%[v1]; vpand %[g0],%[v0],%[v0]; vpand %[g1],%[v1],%[v1]; vpand %[h0],%[v0],%[v0]; vpand %[h1],%[v1],%[v1]; vpand %[i0],%[v0],%[v0]; vpand %[i1],%[v1],%[v1]; vpand %[j0],%[v0],%[v0]; vpand %[j1],%[v1],%[v1]; vmovdqu %[v0],%[o0]; vmovdqu %[v1],%[o1]; ":[v0]"=&x"(v0),[o0]"+m"(*(unsigned char(*)[32])(out+i+0)),[v1]"=&x"(v1),[o1]"+m"(*(unsigned char(*)[32])(out+i+32)):[a0]"m"(*(const unsigned char(*)[32])(p[0]+i+0)),[a1]"m"(*(const unsigned char(*)[32])(p[0]+i+32)),[b0]"m"(*(const unsigned char(*)[32])(p[1]+i+0)),[b1]"m"(*(const unsigned char(*)[32])(p[1]+i+32)),[c0]"m"(*(const unsigned char(*)[32])(p[2]+i+0)),[c1]"m"(*(const unsigned char(*)[32])(p[2]+i+32)),[d0]"m"(*(const unsigned char(*)[32])(p[3]+i+0)),[d1]"m"(*(const unsigned char(*)[32])(p[3]+i+32)),[e0]"m"(*(const unsigned char(*)[32])(p[4]+i+0)),[e1]"m"(*(const unsigned char(*)[32])(p[4]+i+32)),[f0]"m"(*(const unsigned char(*)[32])(p[5]+i+0)),[f1]"m"(*(const unsigned char(*)[32])(p[5]+i+32)),[g0]"m"(*(const unsigned char(*)[32])(p[6]+i+0)),[g1]"m"(*(const unsigned char(*)[32])(p[6]+i+32)),[h0]"m"(*(const unsigned char(*)[32])(p[7]+i+0)),[h1]"m"(*(const unsigned char(*)[32])(p[7]+i+32)),[i0]"m"(*(const unsigned char(*)[32])(p[8]+i+0)),[i1]"m"(*(const unsigned char(*)[32])(p[8]+i+32)),[j0]"m"(*(const unsigned char(*)[32])(p[9]+i+0)),[j1]"m"(*(const unsigned char(*)[32])(p[9]+i+32)));}
for(;i<bytes;++i)out[i]&=p[0][i]&p[1][i]&p[2][i]&p[3][i]&p[4][i]&p[5][i]&p[6][i]&p[7][i]&p[8][i]&p[9][i];
}
}
void PreSieve::preSieve(Vector<ad>& sieve, unsigned __int128 segmentLow)
{
uint8_t* sieve8 = (uint8_t*) sieve.data();
ad sieveBytes = g_logSieveBytes;
for (int pass=0; pass < 2; ++pass)
{
int base = pass * 10;
int K=10;
ad pos[10];
ad q=ad(segmentLow)/30;if(!pass){pos[0]=q%5957;pos[1]=q%6479;pos[2]=q%6409;pos[3]=q%8159;pos[4]=q%8471;pos[5]=q%9071;pos[6]=q%10123;pos[7]=q%10679;pos[8]=q%10919;pos[9]=q%11591;}else{pos[0]=q%11857;pos[1]=q%11899;pos[2]=q%12403;pos[3]=q%12533;pos[4]=q%13261;pos[5]=q%13483;pos[6]=q%13837;pos[7]=q%13493;pos[8]=q%13589;pos[9]=q%12317;}
ad offset=0;
while (offset < sieveBytes)
{
ad b=sieveBytes - offset;
for (int t=0;t<K;t++) b=std::min(b, ad(preSieveTableSizes[base+t] - pos[t]));
b=std::min(sieveBytes-offset,(b+1023)&~ad(1023));
if (!b) break;
const uint8_t* pp[10];
for (int t=0;t<K;t++) pp[t]=preSieveTables[base+t] + pos[t];
if (pass==0) ps1_big(pp,&sieve8[offset],b);
else ps2_big(pp,&sieve8[offset],b);
for (int t=0;t<K;t++){ pos[t]+=b; pos[t] -= preSieveTableSizes[base+t]*(pos[t]>=preSieveTableSizes[base+t]); }
offset += b;
}
}
if (segmentLow <= getMaxPrime())
{
ad i=segmentLow / 30;
Array<uint8_t, 8> primeBits={ 0xff, 0xef, 0x77, 0x3f, 0xdb, 0xed, 0x9e, 0xfc };
ASSERT(sieveBytes >= primeBits.size());
for (std::size_t j=0; i + j < primeBits.size(); j++)
sieve8[j]=primeBits[i + j];
}
}
}
#undef CHECK_FINISHED
#ifndef ERAT_HPP
#define ERAT_HPP
#ifndef CTZ_HPP
#define CTZ_HPP
#include <stdint.h>
#if defined(__x86_64__) || \
defined(_M_X64)
#define IS_X64
#endif
#if defined(__BMI__) || \
(defined(_MSC_VER) && defined(__AVX2__))
#define HAS_TZCNT
#endif
#if (defined(__GNUC__) || \
defined(__clang__)) && \
defined(__x86_64__)
#define HAS_CTZ64
#define CTZ64_SUPPORTS_ZERO
namespace primesieve {
ALWAYS_INLINE ad ctz64(ad x)
{
#if defined(HAS_TZCNT)
__asm__("tzcnt %1, %0" : "=r"(x) : "r"(x));
return x;
#else
__asm__("rep bsf %1, %0" : "=r"(x) : "0"(x));
ASSERT(x <= 64);
return x;
#endif
}
}
#elif (defined(__GNUC__) || \
defined(__clang__)) && \
defined(__aarch64__)
#define HAS_CTZ64
#define CTZ64_SUPPORTS_ZERO
namespace primesieve {
ALWAYS_INLINE ad ctz64(ad x)
{
__asm__("rbit %0, %1 \n\t"
"clz %0, %0  \n\t"
: "=r" (x)
: "r" (x));
return x;
}
}
#elif defined(_MSC_VER) && \
defined(HAS_TZCNT) && \
__has_include(<immintrin.h>)
#include <immintrin.h>
#include <x86intrin.h>
#define HAS_CTZ64
#define CTZ64_SUPPORTS_ZERO
#define ctz64(x) _tzcnt_u64(x)
#elif __cplusplus >= 202002L && \
__has_include(<bit>) && \
(!defined(IS_X64) || defined(HAS_TZCNT))
#include <bit>
#define CTZ64_SUPPORTS_ZERO
#define HAS_CTZ64
namespace primesieve {
ALWAYS_INLINE int ctz64(ad x)
{
return std::countr_zero(x);
}
}
#elif defined(__GNUC__) || \
__has_builtin(__builtin_ctzl)
#define HAS_CTZ64
namespace primesieve {
ALWAYS_INLINE int ctz64(ad x)
{
ASSERT(x != 0);
#if __cplusplus >= 201703L
if constexpr(sizeof(int) >= sizeof(ad))
return __builtin_ctz(x);
else if constexpr(sizeof(long) >= sizeof(ad))
return __builtin_ctzl(x);
else if constexpr(sizeof(long long) >= sizeof(ad))
return __builtin_ctzll(x);
#else
return __builtin_ctzll(x);
#endif
}
}
#elif defined(_MSC_VER) && \
defined(_WIN64) && \
__has_include(<intrin.h>)
#include <intrin.h>
#define HAS_CTZ64
namespace primesieve {
ALWAYS_INLINE int ctz64(ad x)
{
ASSERT(x != 0);
unsigned long r;
_BitScanForward64(&r, x);
return (int) r;
}
}
#endif
#endif
#include <stdint.h>
namespace primesieve {
class MemoryPool;
class Erat
{
public:
ad getStop() const;
protected:
ad start_=0;
ad stop_=0;
ad segmentLow_=~0ull;
ad segmentHigh_=0;
Vector<ad> sieve_;
Erat()=default;
Erat(ad, ad);
void init(ad, ad, ad, MemoryPool& memoryPool);
void addSievingPrime(ad);
NOINLINE void sieveSegment();
bool hasNextSegment() const;
bool lastSegment_=true;
static ad nextPrime(ad, ad);
private:
ad maxEratSmall_=0;
ad maxEratMedium_=0;
EratSmall eratSmall_;
EratBig eratBig_;
EratMedium eratMedium_;
static ad byteRemainder(ad);
static ad getL1CacheSize();
void initAlgorithms(ad maxSieveBytes, MemoryPool&);
void preSieve();
void crossOff();
void sieveLastSegment();
};
ALWAYS_INLINE ad Erat::nextPrime(ad bits, ad low)
{
#if defined(CTZ64_SUPPORTS_ZERO)
auto bitIndex=ctz64(bits);
ad bitValue=bitValues[bitIndex];
#elif defined(HAS_CTZ64)
auto bitIndex=ctz64(bits | (1ull << 63));
ad bitValue=bitValues[bitIndex];
#else
ad debruijn=0x3F08A4C6ACB9DBD;
ad hash = ((bits ^ (bits - 1)) * debruijn) >> 58;
ad bitValue=bruijnBitValues[hash];
#endif
ad prime=low + bitValue;
return prime;
}
ALWAYS_INLINE void Erat::addSievingPrime(ad prime)
{
if (prime > maxEratMedium_) eratBig_.addSievingPrime(prime, segmentLow_);
else if (prime > maxEratSmall_) eratMedium_.addSievingPrime(prime, segmentLow_);
else eratSmall_.addSievingPrime(prime, segmentLow_);
}
ALWAYS_INLINE ad Erat::getStop() const
{
return stop_;
}
}
#endif
#include <stdint.h>
#include <algorithm>
#include <limits>
namespace {
const primesieve::Array<uint8_t, 37> unsetSmaller =
{
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xfe, 0xfe, 0xfe, 0xfe, 0xfc, 0xfc, 0xf8, 0xf8,
0xf8, 0xf8, 0xf0, 0xf0, 0xe0, 0xe0, 0xe0, 0xe0,
0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0x80, 0x80,
0x00, 0x00, 0x00, 0x00, 0x00
};
const primesieve::Array<uint8_t, 37> unsetLarger =
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x01, 0x01, 0x01, 0x03, 0x03, 0x07, 0x07, 0x07,
0x07, 0x0f, 0x0f, 0x1f, 0x1f, 0x1f, 0x1f, 0x3f,
0x3f, 0x3f, 0x3f, 0x3f, 0x3f, 0x7f, 0x7f, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff
};
}
namespace primesieve {
Erat::Erat(ad start, ad stop) :
start_(start),
stop_(stop)
{ }
void Erat::init(ad start,
ad stop,
ad maxSieveSize,
MemoryPool& memoryPool)
{
if_unlikely(start > stop ||
start >= std::numeric_limits<ad>::max())
return;
ASSERT(start >= 7);
ASSERT(maxSieveSize >= 16);
ASSERT(maxSieveSize <= 8192);
start_=start;
stop_=stop;
ad maxSieveBytes=maxSieveSize << 10;
initAlgorithms(maxSieveBytes, memoryPool);
}
ad Erat::getL1CacheSize(){return 32768;}
void Erat::initAlgorithms(ad maxSieveBytes,
MemoryPool& memoryPool)
{
ad sqrtStop=isqrt(stop_);
ad l1CacheSize=getL1CacheSize();
l1CacheSize=inBetween(16 << 10, l1CacheSize, 8192 << 10);
l1CacheSize = ceilDiv(l1CacheSize, sizeof(ad)) * sizeof(ad);
maxSieveBytes = ceilDiv(maxSieveBytes, sizeof(ad)) * sizeof(ad);
ad minSieveBytes=std::min(l1CacheSize, maxSieveBytes);
ad sieveBytes = ad(sqrtStop * config::FACTOR_SIEVESIZE);
if (sieveBytes > minSieveBytes)
sieveBytes -= sieveBytes % minSieveBytes;
sieveBytes=inBetween(minSieveBytes, sieveBytes, maxSieveBytes);
sieveBytes=inBetween(16 << 10, sieveBytes, 8192 << 10);
minSieveBytes=std::min(l1CacheSize, sieveBytes);
maxEratSmall_ = (ad) (minSieveBytes * config::FACTOR_ERATSMALL);
maxEratMedium_ = (ad) (sieveBytes * config::FACTOR_ERATMEDIUM);
if (sqrtStop > maxEratMedium_)
{
sieveBytes=floorPow2(sieveBytes);
minSieveBytes=std::min(l1CacheSize, sieveBytes);
maxEratSmall_ = (ad) (minSieveBytes * config::FACTOR_ERATSMALL);
maxEratMedium_ = (ad) (sieveBytes * config::FACTOR_ERATMEDIUM);
}
maxEratSmall_=std::min(maxEratSmall_, sqrtStop);
maxEratMedium_=std::min(maxEratMedium_, sqrtStop);
ad rem=byteRemainder(start_);
ad dist = sieveBytes * 30 + 6;
segmentLow_=start_ - rem;
segmentHigh_=checkedAdd(segmentLow_, dist);
segmentHigh_=std::min(segmentHigh_, stop_);
if (segmentHigh_ >= stop_ &&
sqrtStop <= maxEratMedium_)
{
ad rem=byteRemainder(stop_);
ad dist=(stop_ - rem) - segmentLow_;
sieveBytes=dist / 30 + 1;
sieveBytes = ceilDiv(sieveBytes, sizeof(ad)) * sizeof(ad);
}
ASSERT(sieveBytes % sizeof(ad) == 0);
g_logSieveBytes = sieveBytes;
sieve_.resize(ceilDiv(sieveBytes + GUARD_BYTES, sizeof(ad)));
__builtin_memset((unsigned char*)sieve_.data() + sieveBytes, 0xFF, GUARD_BYTES);
g_guardPending = 0;
if (sqrtStop > PreSieve::getMaxPrime())
eratSmall_.init(stop_, l1CacheSize, maxEratSmall_);
if (sqrtStop > maxEratSmall_)
eratMedium_.init(stop_, maxEratMedium_, memoryPool);
if (sqrtStop > maxEratMedium_)
eratBig_.init(stop_, sqrtStop, sieve_, memoryPool);
}
bool Erat::hasNextSegment() const
{
return segmentLow_ < stop_;
}
ad Erat::byteRemainder(ad n)
{
ASSERT(n >= 7);
return (n - 7) % 30 + 7;
}
void Erat::sieveSegment()
{
lastSegment_=!(segmentHigh_ < stop_);
if (segmentHigh_ < stop_)
{
preSieve();
{unsigned char* gs=(unsigned char*)sieve_.data();
 if(g_guardPending){std::size_t gn=GUARD_BYTES<g_logSieveBytes?GUARD_BYTES:g_logSieveBytes;for(std::size_t j=0;j<gn;j++)gs[j]&=g_guardSave[j];g_guardPending=0;}
 __builtin_memset(gs+g_logSieveBytes,0xFF,GUARD_BYTES);}
crossOff();
{__builtin_memcpy(g_guardSave,(unsigned char*)sieve_.data()+g_logSieveBytes,GUARD_BYTES);g_guardPending=1;}
ad dist = g_logSieveBytes * 30;
segmentLow_=checkedAdd(segmentLow_, dist);
segmentHigh_=checkedAdd(segmentHigh_, dist);
segmentHigh_=std::min(segmentHigh_, stop_);
}
else
{ lastSegment_=true; sieveLastSegment(); }
}
void Erat::sieveLastSegment()
{
ad rem=byteRemainder(stop_);
ad dist=(stop_ - rem) - segmentLow_;
ad sieveBytes=dist / 30 + 1;
sieve_.resize(ceilDiv(sieveBytes, sizeof(ad)));
g_logSieveBytes = sieve_.size() * sizeof(ad);
preSieve();
if(g_guardPending){unsigned char*gs=(unsigned char*)sieve_.data();std::size_t gn=GUARD_BYTES<g_logSieveBytes?GUARD_BYTES:g_logSieveBytes;for(std::size_t j=0;j<gn;j++)gs[j]&=g_guardSave[j];g_guardPending=0;}
crossOff();
uint8_t* sieve = (uint8_t*) sieve_.data();
sieve[sieveBytes - 1] &= unsetLarger[rem];
ad i=sieveBytes;
for (; i % sizeof(ad); i++)
sieve[i]=0;
segmentLow_=stop_;
}
void Erat::preSieve()
{
PreSieve::preSieve(sieve_, segmentLow_);
if (segmentLow_ <= start_)
{
ad rem=byteRemainder(start_);
uint8_t* sieve = (uint8_t*) sieve_.data();
sieve[0] &= unsetSmaller[rem];
}
}
void Erat::crossOff()
{
eratSmall_.ovr_=!lastSegment_;
if (eratSmall_.hasSievingPrimes())
eratSmall_.crossOff(sieve_);
if (eratMedium_.hasSievingPrimes())
eratMedium_.crossOff(sieve_);
if (eratBig_.hasSievingPrimes())
eratBig_.crossOff(sieve_);
}
}
struct RootBasePrimes{uint32_t p[9592]{};constexpr RootBasePrimes(){bool composite[100001]={};unsigned count=0;for(unsigned i=2;i<=100000;i++)if(!composite[i]){p[count++]=i;if(ad(i)*i<=100000)for(unsigned j=i*i;j<=100000;j+=i)composite[j]=true;}}};
static constexpr RootBasePrimes baseprimes{};
extern "C" const ad prefImage[];
asm(R"PB(
.altmacro
.pushsection .rodata
.balign 64
.global prefImage
prefImage:
.macro startWord i,phase
.set .Lprime\i,.Lmask\phase
.endm
.macro markWord i,b
.set .Lprime\i,(.Lprime\i) & (~(1<<\b))
.endm
.macro putWord i
.quad .Lprime\i
.endm
.macro primeStrike p
 .irp residue,1,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,121,127,131,137,139,143,149,151,157,163,167,169,173,179,181,187,191,193,197,199,209
 .set .Lstart,(\p*((((\p-\residue)+210-1)/210)*210+\residue))
 .if .Lstart<3932160
 .rept 1+((3932160-1-.Lstart)/(210*\p))
 markWord %(.Lstart/64),%(.Lstart%64)
 .set .Lstart,.Lstart+210*\p
 .endr
 .endif
 .endr
.endm
.set .Lmask0,0x28208a20a08a2802
.set .Lmask1,0x820228a202088288
.set .Lmask2,0x8828228820a08a08
.set .Lmask3,0x28828228a00a00a2
.set .Lmask4,0xa28808220a20a082
.set .Lmask5,0x8a20828228220808
.set .Lmask6,0x8a28028028a20a0
.set .Lmask7,0x208828828208a20a
.set .Lmask8,0xa08a08820228a20
.set .Lmask9,0xa00a2882822882
.set .Lmask10,0xa20a08228828228a
.set .Lmask11,0x8220808a28808220
.set .Lmask12,0x28a20a08a2082822
.set .Lmask13,0x208a20a08a280280
.set .Lmask14,0x228a20208828828
.set .Lmask15,0x28228820a08a0882
.set .Lmask16,0x828228a00a00a288
.set .Lmask17,0x8808220a20a08228
.set .Lmask18,0x20828228220808a2
.set .Lmask19,0xa28028028a20a08a
.set .Lmask20,0x8828828208a20a08
.set .Lmask21,0x8a08820228a2020
.set .Lmask22,0xa00a28828228820a
.set .Lmask23,0xa08228828228a00
.set .Lmask24,0x20808a28808220a2
.set .Lmask25,0xa20a08a208282282
.set .Lmask26,0x8a20a08a28028028
.set .Lmask27,0x28a2020882882820
.set .Lmask28,0x228820a08a088202
.set .Lmask29,0x8228a00a00a28828
.set .Lmask30,0x8220a20a0822882
.set .Lmask31,0x828228220808a288
.set .Lmask32,0x8028028a20a08a20
.set .Lmask33,0x28828208a20a08a2
.set .Lmask34,0xa08820228a202088
.set .Lmask35,0xa28828228820a08
.set .Lmask36,0x8228828228a00a0
.set .Lmask37,0x808a28808220a20a
.set .Lmask38,0xa08a20828228220
.set .Lmask39,0x20a08a28028028a2
.set .Lmask40,0xa20208828828208a
.set .Lmask41,0x8820a08a08820228
.set .Lmask42,0x28a00a00a2882822
.set .Lmask43,0x220a20a082288282
.set .Lmask44,0x8228220808a28808
.set .Lmask45,0x28028a20a08a2082
.set .Lmask46,0x828208a20a08a280
.set .Lmask47,0x8820228a20208828
.set .Lmask48,0x28828228820a08a0
.set .Lmask49,0x228828228a00a00a
.set .Lmask50,0x8a28808220a20a08
.set .Lmask51,0x8a2082822822080
.set .Lmask52,0xa08a28028028a20a
.set .Lmask53,0x208828828208a20
.set .Lmask54,0x20a08a08820228a2
.set .Lmask55,0xa00a00a288282288
.set .Lmask56,0xa20a08228828228
.set .Lmask57,0x28220808a2880822
.set .Lmask58,0x28a20a08a208282
.set .Lmask59,0x8208a20a08a28028
.set .Lmask60,0x20228a2020882882
.set .Lmask61,0x828228820a08a088
.set .Lmask62,0x8828228a00a00a28
.set .Lmask63,0x28808220a20a0822
.set .Lmask64,0xa20828228220808a
.set .Lmask65,0x8a28028028a20a08
.set .Lmask66,0x8828828208a20a0
.set .Lmask67,0xa08a08820228a202
.set .Lmask68,0xa00a28828228820
.set .Lmask69,0x20a08228828228a0
.set .Lmask70,0x220808a28808220a
.set .Lmask71,0x8a20a08a20828228
.set .Lmask72,0x8a20a08a2802802
.set .Lmask73,0x228a202088288282
.set .Lmask74,0x8228820a08a08820
.set .Lmask75,0x28228a00a00a2882
.set .Lmask76,0x808220a20a082288
.set .Lmask77,0x828228220808a28
.set .Lmask78,0x28028028a20a08a2
.set .Lmask79,0x828828208a20a08a
.set .Lmask80,0x8a08820228a20208
.set .Lmask81,0xa28828228820a0
.set .Lmask82,0xa08228828228a00a
.set .Lmask83,0x808a28808220a20
.set .Lmask84,0x20a08a2082822822
.set .Lmask85,0xa20a08a28028028a
.set .Lmask86,0x8a20208828828208
.set .Lmask87,0x28820a08a0882022
.set .Lmask88,0x228a00a00a288282
.set .Lmask89,0x8220a20a08228828
.set .Lmask90,0x28228220808a2880
.set .Lmask91,0x28028a20a08a208
.set .Lmask92,0x8828208a20a08a28
.set .Lmask93,0x8820228a2020882
.set .Lmask94,0xa28828228820a08a
.set .Lmask95,0x8228828228a00a00
.set .Lmask96,0x8a28808220a20a0
.set .Lmask97,0xa08a208282282208
.set .Lmask98,0xa08a28028028a20
.set .Lmask99,0x20208828828208a2
.set .Lmask100,0x820a08a08820228a
.set .Lmask101,0x8a00a00a28828228
.set .Lmask102,0x20a20a0822882822
.set .Lmask103,0x228220808a288082
.set .Lmask104,0x8028a20a08a20828
.set .Lpi,0
.rept 3932160/64
startWord %.Lpi,%(.Lpi%105)
.set .Lpi,.Lpi+1
.endr
.irp p,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997,1009,1013,1019,1021,1031,1033,1039,1049,1051,1061,1063,1069,1087,1091,1093,1097,1103,1109,1117,1123,1129,1151,1153,1163,1171,1181,1187,1193,1201,1213,1217,1223,1229,1231,1237,1249,1259,1277,1279,1283,1289,1291,1297,1301,1303,1307,1319,1321,1327,1361,1367,1373,1381,1399,1409,1423,1427,1429,1433,1439,1447,1451,1453,1459,1471,1481,1483,1487,1489,1493,1499,1511,1523,1531,1543,1549,1553,1559,1567,1571,1579,1583,1597,1601,1607,1609,1613,1619,1621,1627,1637,1657,1663,1667,1669,1693,1697,1699,1709,1721,1723,1733,1741,1747,1753,1759,1777,1783,1787,1789,1801,1811,1823,1831,1847,1861,1867,1871,1873,1877,1879,1889,1901,1907,1913,1931,1933,1949,1951,1973,1979
primeStrike \p
.endr
.set .Lprime0,(.Lprime0 & (~2))|0xac
.set .Lpi,0
.rept 3932160/64
putWord %.Lpi
.set .Lpi,.Lpi+1
.endr
.purgem startWord,markWord,putWord,primeStrike
.popsection
.noaltmacro
)PB");
namespace base_stream {
class Generator : public primesieve::Erat {
primesieve::MemoryPool pool;
public:
template<class F> void segments(ad n,F fn) {
init(3932167,n-1,512,pool);
size_t active=46;
while(hasNextSegment()){while(active<9592&&ad(baseprimes.p[active])*baseprimes.p[active]<=segmentHigh_)addSievingPrime(baseprimes.p[active++]);ad low=segmentLow_;sieveSegment();fn(low,(const unsigned char*)sieve_.data(),g_logSieveBytes);}
}
};
}
namespace root_sieve_expand {
struct Lookup{uint32_t a[256]{};constexpr Lookup(){const unsigned off[8]={7,11,13,17,19,23,29,31};for(unsigned v=0;v<256;v++)for(unsigned k=0;k<8;k++)if(v>>k&1)a[v]|=1u<<off[k];}};
static constexpr Lookup table{};
}
static inline __m256i ld32(const void*p){__m256i v;asm("vmovdqu %1,%0":"=x"(v):"m"(*(const unsigned char(*)[32])p));return v;}
static inline void st240(unsigned char*d,const unsigned char*s){
if(uintptr_t(d)&31){
_mm_stream_si128((__m128i*)d,_mm_load_si128((const __m128i*)s));
#pragma GCC unroll 7
for(unsigned i=0;i<7;i++)_mm256_stream_si256((__m256i*)(d+16+32*i),ld32(s+16+32*i));
}else{
#pragma GCC unroll 7
for(unsigned i=0;i<7;i++)_mm256_stream_si256((__m256i*)(d+32*i),ld32(s+32*i));
_mm_stream_si128((__m128i*)(d+224),_mm_load_si128((const __m128i*)(s+224)));
}
}
void sieve(ad input_n,char*dest){constexpr ad n=UINT64_C(100000000);if(input_n!=n)__builtin_trap();
auto*out=(unsigned char*)dest;const size_t total=(n+7)/8;
if(n<8){if(n)*out=(unsigned char)(0xacu&((1u<<n)-1));return;}
if((uintptr_t(out)&31)==0){for(unsigned i=0;i<15360;i++)_mm256_stream_si256((__m256i*)out+i,_mm256_load_si256((const __m256i*)prefImage+i));}else __builtin_memcpy(out,prefImage,491520);
ad carry=0;
constexpr ad mask=[](){ad m=0;for(unsigned x:{7,11,13,17,19,23,29,31})m|=(1ull<<x)|(1ull<<(x+30));return m;}();
const __m128i root_n0_base=_mm_setr_epi8(0,-128,0,-128,0,-128,0,-128,0,-128,0,-128,0,-128,0,-128);
const __m128i root_n1_base=_mm_setr_epi8(0,0,8,8,32,32,40,40,0,0,8,8,32,32,40,40);
const __m128i root_n2_base=_mm_setr_epi8(0,0,0,0,0,0,0,0,2,2,2,2,2,2,2,2);
const __m128i root_nh2_base=_mm_setr_epi8(0,8,-128,-120,0,8,-128,-120,0,8,-128,-120,0,8,-128,-120);
const __m128i root_nh3_base=_mm_setr_epi8(0,0,0,0,32,32,32,32,-128,-128,-128,-128,-96,-96,-96,-96);
const __m256i root_n0=_mm256_broadcastsi128_si256(root_n0_base);
const __m256i root_n1=_mm256_broadcastsi128_si256(root_n1_base);
const __m256i root_n2=_mm256_broadcastsi128_si256(root_n2_base);
const __m256i root_nh2=_mm256_broadcastsi128_si256(root_nh2_base);
const __m256i root_nh3=_mm256_broadcastsi128_si256(root_nh3_base);
const __m256i root_nmask=_mm256_set1_epi8(15),root_ncarry=_mm256_set1_epi32(2),root_nshift=_mm256_setr_epi32(0,2,4,6,0,2,4,6);
base_stream::Generator generator;
generator.segments(n,[&](ad low,const unsigned char*src,size_t bytes){
size_t pos=low>>3;
size_t j=0;
alignas(32) unsigned char block[512];unsigned char*pcur=block,*pprev=block+256;bool pk=0;
if(!(uintptr_t(out+pos)&15))for(;j+64<=bytes&&pos+240<=total;j+=64,pos+=240){
#pragma GCC unroll 2
for(unsigned k=0;k<2;k++){
const auto root_nv=_mm256_loadu_si256((const __m256i*)(src+j+32*k));
const auto root_nlo=_mm256_and_si256(root_nv,root_nmask),root_nhi=_mm256_and_si256(_mm256_srli_epi16(root_nv,4),root_nmask);
const auto root_prev=_mm256_alignr_epi8(root_nv,_mm256_permute2x128_si256(root_nv,root_nv,0x08),15);
const auto root_nc=_mm256_and_si256(_mm256_srli_epi16(root_prev,6),root_ncarry);
const auto root_b0=_mm256_or_si256(_mm256_shuffle_epi8(root_n0,root_nlo),_mm256_or_si256(root_nc,_mm256_set_epi64x(0,0,0,carry)));
const auto root_b1=_mm256_shuffle_epi8(root_n1,root_nlo);
const auto root_b2=_mm256_or_si256(_mm256_shuffle_epi8(root_n2,root_nlo),_mm256_shuffle_epi8(root_nh2,root_nhi));
const auto root_b3=_mm256_shuffle_epi8(root_nh3,root_nhi);
const auto root_l0=_mm256_unpacklo_epi8(root_b0,root_b1),root_l1=_mm256_unpackhi_epi8(root_b0,root_b1);
const auto root_h0=_mm256_unpacklo_epi8(root_b2,root_b3),root_h1=_mm256_unpackhi_epi8(root_b2,root_b3);
const auto root_o0=_mm256_srlv_epi32(_mm256_unpacklo_epi16(root_l0,root_h0),root_nshift);
const auto root_o1=_mm256_srlv_epi32(_mm256_unpackhi_epi16(root_l0,root_h0),root_nshift);
const auto root_o2=_mm256_srlv_epi32(_mm256_unpacklo_epi16(root_l1,root_h1),root_nshift);
const auto root_o3=_mm256_srlv_epi32(_mm256_unpackhi_epi16(root_l1,root_h1),root_nshift);
_mm_storeu_si128((__m128i*)(pcur+120*k+0),_mm256_castsi256_si128(root_o0));
_mm_storeu_si128((__m128i*)(pcur+120*k+15),_mm256_castsi256_si128(root_o1));
_mm_storeu_si128((__m128i*)(pcur+120*k+30),_mm256_castsi256_si128(root_o2));
_mm_storeu_si128((__m128i*)(pcur+120*k+45),_mm256_castsi256_si128(root_o3));
_mm_storeu_si128((__m128i*)(pcur+120*k+60),_mm256_extracti128_si256(root_o0,1));
_mm_storeu_si128((__m128i*)(pcur+120*k+75),_mm256_extracti128_si256(root_o1,1));
_mm_storeu_si128((__m128i*)(pcur+120*k+90),_mm256_extracti128_si256(root_o2,1));
_mm_storeu_si128((__m128i*)(pcur+120*k+105),_mm256_extracti128_si256(root_o3,1));
carry=(unsigned(_mm256_movemask_epi8(root_nv))>>30)&2u;
}
if(pk)st240(out+pos-240,pprev);
{unsigned char*t=pcur;pcur=pprev;pprev=t;}pk=1;
}
if(pk)st240(out+pos-240,pprev);
_mm_sfence();
for(;j<bytes&&pos<total;j+=4){
uint32_t v;__builtin_memcpy(&v,src+j,4);
ad a=_pdep_u64(v,mask),b=_pdep_u64(v>>16,mask>>4);
ad lo=a|carry,hi=b;carry=ad(v>>31)<<1;
if(pos+16<=total)_mm_storeu_si128((__m128i*)(out+pos),_mm_set_epi64x((long long)hi,(long long)lo));
else{unsigned char tail[16];__builtin_memcpy(tail,&lo,8);__builtin_memcpy(tail+8,&hi,8);__builtin_memcpy(out+pos,tail,std::min<size_t>(16,total-pos));}
pos+=15;
}
});
_mm_sfence();out[0]|=0x2c;
if(n&7)out[total-1]&=(1u<<(n&7))-1;
}

CompilationN/AN/ACompile OKScore: N/A

Testcase #16.573 ms12 MB + 328 KBAcceptedScore: 100


Judge Duck Online | 评测鸭在线
Server Time: 2026-11-23 12:28:04 | Loaded in 1 ms | Server Status
个人娱乐项目,仅供学习交流使用 | 捐赠