{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "bcc91029",
   "metadata": {},
   "source": [
    "# CR44 · Primitive roots and discrete logarithms\n",
    "\n",
    "The order of g is the first positive exponent giving 1. A primitive root modulo prime p has order p−1. Inversion of exponentiation is the discrete-logarithm problem.\n",
    "\n",
    "Foundational concepts; prerequisite: CR41.\n",
    "\n",
    "**Scope:** Small synthetic parameters; educational mathematics, not production cryptography."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "concept044",
   "source": [
    "## Primitive roots and discrete logarithms\n",
    "\n",
    "The order of an element g is the smallest positive t with gᵗ≡1. A primitive root modulo prime p generates all p−1 nonzero residues.\n",
    "\n",
    "**Mathematical / protocol foundations:** Enumerate g¹,g²,… reducing each product until repetition. Solving h=gˣ mod p for x is the discrete logarithm problem; small classroom fields are trivial, large approved groups are selected for hardness.\n",
    "\n",
    "**Worked teaching example and interpretation:** Modulo 7, powers of 3 are 3,2,6,4,5,1, so order=6 and log₃(4)=4 in this cycle. Do not infer production security from the small example.\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-44",
   "source": [
    "## Mathematical foundations\n",
    "\n",
    "The order of nonzero g modulo prime p is the smallest positive k with g^k≡1. If the order is p−1, g generates all nonzero residues and is a primitive root. The discrete logarithm asks which exponent maps to a given residue, relative to a chosen base.\n",
    "\n",
    "**Defining equation:** ordₚ(g)=min{k>0:g^k≡1 mod p}\n",
    "\n",
    "**Worked example:** Modulo 19, g=10 has order 18; the sequence cycles through every nonzero residue. A nonprimitive base visits only a subgroup.\n",
    "\n",
    "**Common misconception:** The logarithm is not an ordinary real-number logarithm. A target outside the generated subgroup has no discrete log to that base.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "54ed17b1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR44 | 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 prime(n):\n",
    "    return n>=2 and all(n%i for i in range(2,math.isqrt(n)+1))\n",
    "\n",
    "DEFAULT={'p': 19, 'g': 10}\n",
    "ALTERNATE={'g': 7}\n",
    "\n",
    "def run(overrides=None):\n",
    "    # Merge only explicitly supplied inputs with the reference baseline.\n",
    "    params={**DEFAULT, **(overrides or {})}\n",
    "    p=params['p']\n",
    "    g=params['g']\n",
    "    if not prime(p) or not 1<=g<p: raise ValueError('prime modulus and nonzero base required')\n",
    "    steps=[];v=1\n",
    "    for i in range(1,p):\n",
    "        v=v*g%p;steps.append({'exponent':i,'residue':v})\n",
    "        if v==1:break\n",
    "    result={'order':len(steps),'primitive':len(steps)==p-1,'distinct_residues':len(set(s['residue'] for s in steps))}\n",
    "    # Independently check the stated mathematical or protocol invariant.\n",
    "    assert result[\"order\"]==result[\"distinct_residues\"] and pow(g,result[\"order\"],p)==1, \"verification failed\"\n",
    "    return {\"steps\":steps,\"result\":result}\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bd97ce0a",
   "metadata": {},
   "source": [
    "## Baseline calculation\n",
    "Inspect each trace row. The final result is separate from intermediate states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f739235c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR44 | 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": "68cb9597",
   "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": "bae70383",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR44 | 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": "eb0e33eb",
   "metadata": {},
   "source": [
    "## Student activity\n",
    "Compare g=10 and g=7 modulo 19. Construct the inverse table and identify unreachable residues.\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-44",
   "source": [
    "## Reproduce the browser experiment\n",
    "\n",
    "Run p=19,g=10. Record each exponent/residue through the first return to 1. Keep p fixed; set g=7, then g=1. Compare order and list unreachable nonzero residues. Build an inverse lookup table for each base.\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:** Test g=2 and g=4 modulo 17; determine their orders and whether each generates all nonzero residues.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}