28 static_assert(std::is_integral_v<I>,
"Integral required");
30 std::vector<I> factors;
32 bool bValueNegative =
false;
33 if constexpr (std::numeric_limits<I>::min() < 0)
37 bValueNegative =
true;
44 while (nValue % 2 == 0)
51 I nMaxFactor =
static_cast<I
>(std::sqrt(nValue));
52 while (i <= nMaxFactor)
54 while (nValue % i == 0)
58 nMaxFactor =
static_cast<I
>(std::sqrt(nValue));
65 factors.push_back(nValue);
68 if constexpr (std::numeric_limits<I>::min() < 0)
69 if (!factors.empty() && bValueNegative)
70 factors[0] = -factors[0];
86 static_assert(std::is_integral_v<I>,
"Integral required");
88 std::vector<bool> isComposite(
static_cast<size_t>(nMaxNumber) + 1,
false);
90 constexpr
size_t first_composite_power_of_two = 4;
91 for (
size_t i = first_composite_power_of_two; i < static_cast<size_t>(nMaxNumber) + 1; i += 2)
93 isComposite[i] =
true;
97 I nStopAt =
static_cast<I
>(std::sqrt(nMaxNumber + 1));
98 while (nNextPrime <= nStopAt)
100 for (I i = nNextPrime * 2; i < nMaxNumber + 1; i += nNextPrime)
101 isComposite[
static_cast<size_t>(i)] =
true;
105 while (nNextPrime <= nMaxNumber && isComposite[
static_cast<size_t>(nNextPrime)])
111 std::vector<I> primes;
112 primes.reserve(
static_cast<size_t>(nMaxNumber / 2));
114 for (I i = 2; i < nMaxNumber + 1; ++i)
115 if (!isComposite[
static_cast<size_t>(i)])
118 primes.shrink_to_fit();
140 inline bool is_prime(
size_t nValue,
double fProbability)
142 if (fProbability < 0)
143 fProbability = -fProbability;
145 if (fProbability >= 1 || std::fabs(fProbability) <= DBL_EPSILON)
148 constexpr
double fLog2 = 0.30102999566;
150 const size_t nTests =
static_cast<size_t>(std::ceil(std::log(1.0 / (1.0 - fProbability)) / fLog2));
152 std::default_random_engine generator(
static_cast<unsigned>(std::time(
nullptr)));
154 std::uniform_int_distribution<size_t> num_dist(2, nValue);
156 for (
size_t i = 0; i < nTests; i++)
158 const size_t nRandomNumber = num_dist(generator);
159 if (
static_cast<size_t>(
pow(nRandomNumber,
static_cast<int>(nValue) - 1)) % nValue != 1)
double pow(T number, int nPower)
Power function for integer power.
std::vector< I > find_primes(I nMaxNumber)
Find all primes between 2 and nMaxNumber.
bool is_prime(size_t nValue)
Is number prime.
std::vector< I > find_prime_factors(I nValue)
Find all prime factors.