TheAlgorithms/JavaScript · error · Error

${a} is not coprime of 26

Error message

${a} is not coprime of 26

What it means

Thrown by isCorrectFormat() when multiplier a is not coprime with 26 (the alphabet size). Affine decryption requires the modular inverse of a mod 26 to exist; that inverse exists only when gcd(a, 26) === 1, i.e. a shares no factor 2 or 13 with 26. Non-coprime a makes decryption ambiguous/impossible.

Source

Thrown at Ciphers/AffineCipher.js:49

/**
 * Argument validation
 * @param {String} str - String to be checked
 * @param {Number} a - A coefficient to be checked
 * @param {Number} b - B coefficient to be checked
 * @return {Boolean} Result of the checking
 */
function isCorrectFormat(str, a, b) {
  if (typeof a !== 'number' || typeof b !== 'number') {
    throw new TypeError('Coefficient a, b should be number')
  }

  if (typeof str !== 'string') {
    throw new TypeError('Argument str should be String')
  }

  if (!CoPrimeCheck(a, 26)) {
    throw new Error(a + ' is not coprime of 26')
  }

  return true
}

/**
 * Find character index based on ASCII order
 * @param {String} char - Character index to be found
 * @return {Boolean} Character index
 */
function findCharIndex(char) {
  return char.toUpperCase().charCodeAt(0) - 'A'.charCodeAt(0)
}

/**
 * Encrypt a Affine Cipher
 * @param {String} str - String to be encrypted
 * @param {Number} a - A coefficient

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Use one of the valid multipliers: 1,3,5,7,9,11,15,17,19,21,23,25.
  2. When generating keys, loop until gcd(a, 26) === 1.
  3. Validate coprimality at the call site before encrypt.

Example fix

// before
encrypt(text, 2, 8) // 2 shares factor with 26
// after
encrypt(text, 5, 8) // 5 coprime with 26
Defensive patterns

Strategy: validation

Validate before calling

function gcd(x, y) { return y === 0 ? x : gcd(y, x % y); }
const validAffineA = [1,3,5,7,9,11,15,17,19,21,23,25];
function isCoprime26(a) { return Number.isInteger(a) && gcd(((a % 26) + 26) % 26, 26) === 1; }

Type guard

/** @param {unknown} a @returns {boolean} */
const isValidAffineMultiplier = a =>
  Number.isInteger(a) && [1,3,5,7,9,11,15,17,19,21,23,25].includes(((a % 26) + 26) % 26);

Try / catch

try { return encrypt(text, a, b); }
catch (e) {
  if (e instanceof Error && /not coprime of 26/.test(e.message)) {
    return encrypt(text, 5, b); // fall back to a known-good multiplier
  }
  throw e;
}

Prevention

When it happens

Trigger: Passing a = 2, 4, 6, 8, 10, 12, 13, 14, ... any even number or any multiple of 13. Valid values are 1,3,5,7,9,11,15,17,19,21,23,25.

Common situations: Picking an arbitrary key, using a = 0 (degenerate), or auto-generating a without the coprimality constraint.

Related errors


AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13). Data as JSON: /api/errors/d56f04e1a0e3aabf. Report an issue: GitHub.