feat: add repunit theorem helpers by nickzerjeski · Pull Request #1892 · TheAlgorithms/JavaScript · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion DIRECTORY.md
79 changes: 79 additions & 0 deletions Maths/RepunitTheorem.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/**
* Repunit theorem helpers.
*
* A repunit of length n is:
* R_n = (10^n - 1) / 9
*
* For a prime p (p != 2, 3, 5), p divides R_n iff ord_p(10) divides n.
* Reference: https://en.wikipedia.org/wiki/Repunit
*/
Comment on lines +1 to +9

Copilot AI Apr 13, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The file header comment says the theorem holds for primes p != 2,5, but it also needs p != 3 (equivalently gcd(p,9)=1). As written, it documents an incorrect condition and matches the buggy behavior for p=3.

Copilot uses AI. Check for mistakes.

const gcd = (a, b) => {
let x = BigInt(a)
let y = BigInt(b)
while (y !== 0n) {
;[x, y] = [y, x % y]
}
return x < 0n ? -x : x
}

const modPow = (base, exp, mod) => {
let result = 1n
let b = BigInt(base) % BigInt(mod)
let e = BigInt(exp)
const m = BigInt(mod)

while (e > 0n) {
if (e & 1n) result = (result * b) % m
b = (b * b) % m
e >>= 1n
}

return result
}

const multiplicativeOrder10 = (prime) => {
const p = BigInt(prime)
if (p <= 1n) throw new RangeError('prime must be > 1')
if (gcd(10n, p) !== 1n) throw new RangeError('10 and prime must be coprime')

// For prime p, ord_p(10) divides p-1.
const upper = p - 1n
for (let k = 1n; k <= upper; k++) {
if (upper % k === 0n && modPow(10n, k, p) === 1n) {
return k
}
}
Comment thread
nickzerjeski marked this conversation as resolved.

throw new Error('multiplicative order not found')
}

const repunitMod = (length, mod) => {
if (!Number.isInteger(length) || length < 1) {
throw new RangeError('length must be a positive integer')
}
const m = BigInt(mod)
if (m <= 0n) throw new RangeError('mod must be > 0')

let remainder = 0n
for (let i = 0; i < length; i++) {
remainder = (remainder * 10n + 1n) % m
}
return remainder
}

const isRepunitDivisibleByPrime = (length, prime) => {
if (!Number.isInteger(length) || length < 1) {
throw new RangeError('length must be a positive integer')
}

const p = BigInt(prime)
if (p === 2n || p === 5n) return false
if (p === 3n) return BigInt(length) % 3n === 0n
if (gcd(10n, p) !== 1n) return false

const order = multiplicativeOrder10(p)
return BigInt(length) % order === 0n
Comment thread
nickzerjeski marked this conversation as resolved.
}

export { multiplicativeOrder10, repunitMod, isRepunitDivisibleByPrime }
50 changes: 50 additions & 0 deletions Maths/test/RepunitTheorem.test.js
Loading