{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e6db6bb3",
   "metadata": {},
   "source": [
    "# CR38 · Extended Euclidean algorithm: three phases\n",
    "\n",
    "Forward division finds gcd; back-substitution rewrites it as ax+ny. Reduce x modulo n to obtain the inverse if gcd=1. Worked example: 20⁻¹ mod 23 = 15.\n",
    "\n",
    "Foundational concepts; prerequisite: CR37.\n",
    "\n",
    "**Scope:** Small synthetic parameters; educational mathematics, not production cryptography."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "concept038",
   "source": [
    "## Extended Euclidean algorithm\n",
    "\n",
    "Euclid replaces a pair by divisor and remainder without changing gcd. EEA expresses the last nonzero remainder as a linear combination of original operands.\n",
    "\n",
    "**Mathematical / protocol foundations:** 23=1·20+3; 20=6·3+2; 3=1·2+1. Back-substitute: 1=3−2=7·3−20=7·23−8·20. Reduce coefficient −8 modulo 23 to 15.\n",
    "\n",
    "**Worked teaching example and interpretation:** Check 20·15≡1. A final gcd other than 1 means no modular inverse. The same procedure supports RSA private exponents and ECC slopes.\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-38",
   "source": [
    "## Mathematical foundations\n",
    "\n",
    "Successive Euclidean divisions replace (r,s) by (s,r−qs) until the second remainder is zero. Each remainder also equals a linear combination of the initial inputs. Track coefficients starting at (1,0) and (0,1), or substitute equations backward.\n",
    "\n",
    "**Defining equation:** r = dividend − q·divisor; g = ax+ny\n",
    "\n",
    "**Worked example:** 23=1·20+3; 20=6·3+2; 3=1·2+1. Back substitute: 1=3−2=7·3−20=7·23−8·20. Thus x=−8, inverse=15.\n",
    "\n",
    "**Common misconception:** The negative Bézout coefficient is valid; reduce it modulo n to obtain a canonical inverse.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e7c93332",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR38 | 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': 20, 'n': 23}\n",
    "ALTERNATE={'a': 421, 'n': 1009}\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",
    "    steps += [{'phase':'Bézout back-substitution coefficients','a':a,'x':x,'n':n,'y':y,'sum':a*x+n*y},{'phase':'reduce and verify','inverse':x%n if g==1 else None,'product_mod_n':a*x%n}]\n",
    "    result={'gcd':g,'x':x,'y':y,'inverse':x%n if g==1 else None}\n",
    "    # Independently check the stated mathematical or protocol invariant.\n",
    "    assert a*result[\"x\"]+n*result[\"y\"]==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": "847c3421",
   "metadata": {},
   "source": [
    "## Baseline calculation\n",
    "Inspect each trace row. The final result is separate from intermediate states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4090c791",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR38 | 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": "7720429c",
   "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": "1a843d41",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR38 | 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": "80efba98",
   "metadata": {},
   "source": [
    "## Student activity\n",
    "Trace the quotients for 20 and 23, write each remainder as a linear combination, then repeat for 421 and 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-38",
   "source": [
    "## Reproduce the browser experiment\n",
    "\n",
    "Run a=20,n=23. Copy the divisions and each remainder coefficient. Use the last nonzero remainder and substitute backward on paper. Verify 20·15 mod 23=1. Repeat for 421,1009. Then use a=10,n=40 to identify the no-inverse case.\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:** Find the Bézout coefficients for 13 and 31 and derive the inverse. Show all three phases.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}