{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "861f7627",
   "metadata": {},
   "source": [
    "# CR37 · Modular inverses and division\n",
    "\n",
    "An inverse x satisfies ax≡1 mod n. Division a/b means a·b⁻¹, defined only when gcd(b,n)=1. The lecture includes 421 mod 1009 and 10 mod 40 (no inverse).\n",
    "\n",
    "Foundational concepts; prerequisite: CR36.\n",
    "\n",
    "**Scope:** Small synthetic parameters; educational mathematics, not production cryptography."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "concept037",
   "source": [
    "## Modular inverse and division\n",
    "\n",
    "An inverse is a residue that multiplies to one, not an ordinary reciprocal. It exists precisely when the operand is coprime to the modulus.\n",
    "\n",
    "**Mathematical / protocol foundations:** a⁻¹ mod n=x if ax≡1. If gcd(a,n)=1, ax+ny=1 gives x by EEA. Division b/a mod n=b·x mod n.\n",
    "\n",
    "**Worked teaching example and interpretation:** 20⁻¹ mod23=15 since 20·15=300=13·23+1. For 10 mod40, gcd=10, so no inverse. Do not divide residues using floating-point arithmetic.\n",
    "\n",
    "Compare corresponding states; for randomized or timed runs compare invariants rather than literal random bytes or timings.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "m291-theory-37",
   "source": [
    "## Mathematical foundations\n",
    "\n",
    "An inverse of a modulo n is an integer x such that ax≡1. It exists exactly when gcd(a,n)=1. Modular division c/a is c multiplied by the inverse of a, not ordinary division. The Euclidean algorithm identifies the gcd and Bézout coefficients.\n",
    "\n",
    "**Defining equation:** ax+ny=gcd(a,n); if gcd=1 then a⁻¹=x mod n\n",
    "\n",
    "**Worked example:** 7⁻¹ mod 17=5; 7·5=35≡1. 10⁻¹ mod 40 does not exist because gcd=10.\n",
    "\n",
    "**Common misconception:** A nonzero element need not have an inverse when the modulus is composite.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2b90284c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR37 | Algorithm and verification =====\n",
    "# ===== Algorithm and verification =====\n",
    "# The function returns the exact intermediate states and verifies the invariant.\n",
    "import math\n",
    "import json\n",
    "\n",
    "def egcd(a,b):\n",
    "    # Track coefficients of a and b alongside the successive remainders.\n",
    "    r,s,t=a,1,0; nr,ns,nt=b,0,1; steps=[]\n",
    "    while nr:\n",
    "        q=r//nr; steps.append({'dividend':r,'divisor':nr,'quotient':q,'remainder':r%nr,'coeff_a':s-q*ns,'coeff_b':t-q*nt})\n",
    "        r,nr=nr,r-q*nr; s,ns=ns,s-q*ns; t,nt=nt,t-q*nt\n",
    "    return r,s,t,steps\n",
    "\n",
    "DEFAULT={'a': 7, 'n': 17}\n",
    "ALTERNATE={'a': 10, 'n': 40}\n",
    "\n",
    "def run(overrides=None):\n",
    "    # Merge only explicitly supplied inputs with the reference baseline.\n",
    "    params={**DEFAULT, **(overrides or {})}\n",
    "    a=params['a']\n",
    "    n=params['n']\n",
    "    g,x,y,steps=egcd(a,n)\n",
    "    result={'gcd':g,'inverse':x%n if g==1 else None,'bezout':a*x+n*y,'verification':a*x%n if g==1 else None}\n",
    "    # Independently check the stated mathematical or protocol invariant.\n",
    "    assert result[\"bezout\"]==math.gcd(a,n) and (result[\"inverse\"] is None or a*result[\"inverse\"]%n==1), \"verification failed\"\n",
    "    return {\"steps\":steps,\"result\":result}\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "debf5912",
   "metadata": {},
   "source": [
    "## Baseline calculation\n",
    "Inspect each trace row. The final result is separate from intermediate states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "349396b9",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR37 | Execute the baseline =====\n",
    "# ===== Execute the baseline =====\n",
    "# Run the default worked example; inspect the intermediate states in order.\n",
    "baseline=run()\n",
    "for step in baseline[\"steps\"]: print(step)\n",
    "print(\"Result:\",baseline[\"result\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8f1ab24e",
   "metadata": {},
   "source": [
    "## Controlled comparison\n",
    "Change the indicated input; leave other inputs unchanged. A baseline is the reference run. A mathematical verification substitutes the result back into its defining equation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "378f6a38",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR37 | Compare the specified alternative =====\n",
    "# ===== Compare the specified alternative =====\n",
    "# Override only the chosen input(s), leaving remaining parameters at baseline.\n",
    "comparison=run(ALTERNATE)\n",
    "for step in comparison[\"steps\"]: print(step)\n",
    "print(\"Result:\",comparison[\"result\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2d762558",
   "metadata": {},
   "source": [
    "## Student activity\n",
    "Compare 7 mod 17 with 10 mod 40. Then use Python to verify inverses of 2,3,11,12 mod 17; 20 mod 23; 13 mod 31; 421 mod 1009.\n",
    "\n",
    "Submit a baseline/alternate table, trace evidence and a justification. Identify which checks passed and what they do not prove."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "m291-evidence-37",
   "source": [
    "## Reproduce the browser experiment\n",
    "\n",
    "Run a=7,n=17; record gcd, inverse and verification. Change to a=10,n=40 and explain why inverse is undefined. Verify 2,3,11,12 modulo 17, 20 modulo 23, 13 modulo 31 and 421 modulo 1009. Use the inverse of 7 to compute 9/7 modulo 17 by hand.\n",
    "\n",
    "Use the same input values in the browser and Python. Keep a table of input, intermediate operation, result, verification and interpretation.\n",
    "\n",
    "**Independent task:** Compute 14⁻¹ mod 31 and verify it; contrast 14 mod 35.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}