{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4a725a4f",
   "metadata": {},
   "source": [
    "# CR52 · Elliptic curves over prime fields\n",
    "\n",
    "For prime p>3 use y²≡x³+ax+b mod p, with 4a³+27b² nonzero modulo p. Enumerate all matching y for each x. The group includes point at infinity O, which has no finite coordinate. Plot discrete points.\n",
    "\n",
    "## Worked calculation\n",
    "p=17,a=b=2: (5,1) satisfies 1≡137 mod 17. There are 18 finite points plus infinity, order 19.\n",
    "\n",
    "## Baseline\n",
    "Enumerate x one at a time. Record right-hand residues and matching y; count points plus infinity.\n",
    "\n",
    "## Controlled investigation\n",
    "Run p=23,a=b=1; then p=17,a=2,b=3. Compare group orders. Try singular a=b=0.\n",
    "\n",
    "**Evidence:** Curve parameters, discriminant residue, x/RHS/y table and group order.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "concept052",
   "source": [
    "## Elliptic curve domains\n",
    "\n",
    "For prime p>3, a short Weierstrass curve is y²=x³+ax+b over GF(p), with 4a³+27b²≠0 mod p. Real curves are continuous, while finite-field points are discrete.\n",
    "\n",
    "**Mathematical / protocol foundations:** Enumerate x,y in 0…p−1 and retain pairs satisfying the congruence. Add the point at infinity O as group identity. Negation is (x,−y mod p).\n",
    "\n",
    "**Worked teaching example and interpretation:** For p=17,a=b=2, P=(5,1): RHS=125+10+2=137≡1=y². Discriminant term 140≡4, so nonsingular. The point set has 18 finite points and O.\n",
    "\n",
    "Compare corresponding states; for randomized or timed runs compare invariants rather than literal random bytes or timings.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d9a04ecc",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR52 | Educational algorithm and validation =====\n",
    "# CR52 | Elliptic curves over prime fields\n",
    "# Execute the named operation; expose states and assert the laboratory 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",
    "def on(P,a,b,p):\n",
    "    return P is None or (isinstance(P,(tuple,list)) and len(P)==2 and all(type(x) is int for x in P) and 0<=P[0]<p and 0<=P[1]<p and (P[1]**2-P[0]**3-a*P[0]-b)%p==0)\n",
    "\n",
    "DEFAULT={'p': 17, 'a': 2, 'b': 2}\n",
    "ALTERNATE={'p': 23, 'a': 1, 'b': 1}\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",
    "    a=params['a']\n",
    "    b=params['b']\n",
    "    if not (all(type(x) is int for x in (p,a,b)) and 5<=p<=97 and prime(p) and -997<=a<=997 and -997<=b<=997 and (4*a**3+27*b*b)%p!=0): raise ValueError('Invalid classroom curve or scalar')\n",
    "    if not prime(p) or p<5 or (4*a**3+27*b*b)%p==0:raise ValueError('invalid curve')\n",
    "    steps=[{'x':x,'rhs':(x**3+a*x+b)%p,'ys':[y for y in range(p) if on((x,y),a,b,p)]} for x in range(p)];points=[[s['x'],y] for s in steps for y in s['ys']];result={'points':points,'order':len(points)+1}\n",
    "    # Independently check the stated mathematical or protocol invariant.\n",
    "    assert all(on(tuple(pt),a,b,p) for pt in result[\"points\"]), \"verification failed\"\n",
    "    return {\"steps\":steps,\"result\":result}\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c71b5844",
   "metadata": {},
   "source": [
    "## Baseline calculation\n",
    "Inspect each trace row. The final result is separate from intermediate states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6edb0833",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR52 | 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": "a81feb19",
   "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": "fdb56081",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR52 | 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": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "# ===== CR52 | Controlled trials =====\n",
    "# Reinitialize defaults on every run. Record actual traces and compare invariants.\n",
    "for settings in [{'b': 3}]:\n",
    "    trial = run(settings)\n",
    "    print(settings, trial[\"result\"])\n",
    "    for state in trial[\"steps\"]: print(state)\n"
   ],
   "id": "f612c7a27645118a"
  },
  {
   "cell_type": "markdown",
   "id": "753de906",
   "metadata": {},
   "source": [
    "## Student activity\n",
    "Run p=23,a=b=1; then p=17,a=2,b=3. Compare group orders. Try singular a=b=0.\n",
    "\n",
    "Submit Curve parameters, discriminant residue, x/RHS/y table and group order.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
