Skip to content

Commit

Permalink
Miller-Rabin & floor sum
Browse files Browse the repository at this point in the history
  • Loading branch information
ttamx committed Nov 27, 2024
1 parent 7cb2512 commit 6569284
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
18 changes: 18 additions & 0 deletions content/number-theory/FloorSum.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#pragma once

/**
* Author: Teetat T.
* Date: 2024-09-21
* Description: Floor sum function.
* $f(a, b, c, n) = \sum_{x=0}^n \lfloor \frac{ax+b}{c} \rfloor$
* becareful when a,b,c are negetive (use custom floor division and mod instead)
* Time: $O(\log a)$
*/

ll floor_sum(ll a,ll b,ll c,ll n){
ll res=n*(n+1)/2*(a/c)+(n+1)*(b/c);
a%=c,b%=c;
if(a==0)return res;
ll m=(a*n+b)/c;
return res+n*m-floor_sum(c,c-b-1,a,m-1);
}
38 changes: 38 additions & 0 deletions content/number-theory/MillerRabin.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* Author: chilli, c1729, Simon Lindholm
* Date: 2019-03-28
* License: CC0
* Source: Wikipedia, https://miller-rabin.appspot.com/
* Description: Deterministic Miller-Rabin primality test.
* Guaranteed to work for numbers up to $7 \cdot 10^{18}$; for larger numbers, use Python and extend A randomly.
* Time: 7 times the complexity of $a^b \mod c$.
* Status: Stress-tested
*/
#pragma once

using ull = uint64_t;

ull modmul(ull a, ull b, ull M) {
ll ret = a * b - M * ull(1.L / M * a * b);
return ret + M * (ret < 0) - M * (ret >= (ll)M);
}
ull modpow(ull b, ull e, ull mod) {
ull ans = 1;
for (; e; b = modmul(b, b, mod), e /= 2)
if (e & 1) ans = modmul(ans, b, mod);
return ans;
}

bool isPrime(ull n) {
if (n < 2 || n % 6 % 4 != 1) return (n | 1) == 3;
ull A[] = {2, 325, 9375, 28178, 450775, 9780504, 1795265022},
s = __builtin_ctzll(n-1), d = n >> s;
for (ull a : A) { // ^ count trailing zeroes
ull p = modpow(a%n, d, n), i = s;
while (p != 1 && p != n - 1 && a % n && i--)
p = modmul(p, p, n);
if (p != n-1 && i != s) return 0;
}
return 1;
}

2 changes: 2 additions & 0 deletions content/number-theory/chapter.tex
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ \chapter{Number Theory}
\kactlimport{euclid.h}
\kactlimport{CRT.hpp}
\kactlimport{phiFunction.hpp}
\kactlimport{FloorSum.hpp}

\section{Prime Numbers}
\kactlimport{MillerRabin.hpp}
\kactlimport{LinearSieve.hpp}
\kactlimport{FastEratosthenes.hpp}
\kactlimport{GolbatchConjecture.hpp}

0 comments on commit 6569284

Please sign in to comment.