{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "18bdfa7d",
   "metadata": {},
   "source": [
    "# CR41 · Repeated squaring and operation counts\n",
    "\n",
    "Binary exponent bits select powers a^(2^i). Repeated squaring reduces every multiplication; the number of steps grows with the exponent bit length.\n",
    "\n",
    "Foundational concepts; prerequisite: CR35.\n",
    "\n",
    "**Scope:** Small synthetic parameters; educational mathematics, not production cryptography."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "concept041",
   "source": [
    "## Square-and-multiply\n",
    "\n",
    "Modular exponentiation avoids enormous intermediate integers by reducing after each multiplication. Binary exponent decomposition determines which successive squares to multiply.\n",
    "\n",
    "**Mathematical / protocol foundations:** a^(u+v)=a^u·a^v. Compute t0=a mod n, tⱼ₊₁=tⱼ² mod n; multiply tⱼ only for set exponent bits. Operation count grows logarithmically with exponent magnitude.\n",
    "\n",
    "**Worked teaching example and interpretation:** For 5¹³ mod23, 13=8+4+1; squares 5,2,4,16. Selected product 5·4·16=320≡21. Reduce after each multiplication for the same result.\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-41",
   "source": [
    "## Mathematical foundations\n",
    "\n",
    "Right-to-left square-and-multiply reads the exponent in binary from its least significant bit. Each iteration squares the current base modulo n; a 1 bit multiplies the accumulator by that base. This avoids materializing huge powers.\n",
    "\n",
    "**Defining equation:** e=Σ bᵢ2^i; r←r·a^(2^i) mod n when bᵢ=1\n",
    "\n",
    "**Worked example:** 27=16+8+2+1; 13^27 mod 55=7. This trace counts one square per processed bit, including the final square even though it is unused.\n",
    "\n",
    "**Common misconception:** Operation counts are not runtime benchmarks or evidence of constant-time execution.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b6c9d360",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR41 | Algorithm and verification =====\n",
    "# ===== Algorithm and verification =====\n",
    "# The function returns the exact intermediate states and verifies the invariant.\n",
    "import json\n",
    "\n",
    "def exptrace(a,e,m):\n",
    "    # Right-to-left square-and-multiply; reduce after every product.\n",
    "    if e<0 or m<2: raise ValueError('Require nonnegative exponent and modulus >= 2')\n",
    "    r=1; b=a%m; steps=[]; i=0\n",
    "    while e:\n",
    "        bit=e&1; old=r\n",
    "        if bit: r=r*b%m\n",
    "        steps.append({'bit_index':i,'selected':bit,'power_residue':b,'accumulator_before':old,'accumulator':r,'next_square':b*b%m}); b=b*b%m; e//=2; i+=1\n",
    "    return r,steps\n",
    "\n",
    "DEFAULT={'a': 13, 'e': 27, 'n': 55}\n",
    "ALTERNATE={'e': 19}\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",
    "    e=params['e']\n",
    "    n=params['n']\n",
    "    v,steps=exptrace(a,e,n)\n",
    "    result={'value':v,'binary_exponent':bin(e),'selected_powers':[2**s['bit_index'] for s in steps if s['selected']],'multiply_count':sum(s['selected'] for s in steps),'square_count':len(steps)}\n",
    "    # Independently check the stated mathematical or protocol invariant.\n",
    "    assert result[\"value\"]==pow(a,e,n), \"verification failed\"\n",
    "    return {\"steps\":steps,\"result\":result}\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1425b895",
   "metadata": {},
   "source": [
    "## Baseline calculation\n",
    "Inspect each trace row. The final result is separate from intermediate states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0a116ef7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR41 | 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": "684341b1",
   "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": "ef70d4c1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR41 | 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": "00d11717",
   "metadata": {},
   "source": [
    "## Student activity\n",
    "Compare exponent 27 and 19. List selected powers, count operations and verify with pow(a,e,n).\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-41",
   "source": [
    "## Reproduce the browser experiment\n",
    "\n",
    "Run a=13,e=27,n=55. Record each exponent bit, power residue, accumulator and square. Keep a,n fixed and set e=19 then e=16. Compare multiplication count, square count and pow(a,e,n).\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 7^23 mod 31 by hand; compare your trace with Python and explain the number of selected powers.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}