Compute greatest common divisors and modular inverses, evaluate powers efficiently, and apply number theory to classical ciphers.
The focus of this experiment is to calculate gcd, Bézout coefficients and Euler totient. Students then derive invertible Affine and Hill transformations under stated moduli, and verify inverse recovery and reject noninvertible keys. The Concepts view explains the operation before the practical work; the Simulation view is used to examine reference and changed inputs, not to substitute for actual measurements.
Learning objectives
Calculate gcd, Bézout coefficients and Euler totient.
Derive invertible Affine and Hill transformations under stated moduli.
Verify inverse recovery and reject noninvertible keys.
Record the relevant inputs, intermediate states and final verification result before changing the reference configuration.
Compare the reference calculation or decision with an independent implementation or authorized observation; state any discrepancy and the applicable model boundary.
Expected learning outcomes
On completion, students can calculate gcd, Bézout coefficients and Euler totient, derive invertible Affine and Hill transformations under stated moduli, and verify inverse recovery and reject noninvertible keys.
Required deliverables
Submit the derivation or state trace for the named operation, the exact reference and changed configurations, the associated simulator or practical evidence, and a short validation statement addressing verify inverse recovery and reject noninvertible keys. Separate predicted values from observations.
Prerequisite knowledge and related learning
Review the foundational terminology in Concepts and confirm readiness using the existing setup instructions. After completion, continue to Stream ciphers — Polynomials and LFSRs.
Environment and experimental methodology
The included teaching workstation and the listed Python/Colab or WSL implementation. Historical and small-number constructions are instructional, not deployment recommendations.
Begin with a manual prediction, record the baseline, change one independent condition at a time, and compare the resulting trace or measurements with the original prediction. Record observations and uncertainty separately from reference values. Follow the experiment’s specific procedure, safety limits, and acceptance checks.
How to investigate Modular arithmetic II — Euclid, totient, Affine and Hill
Compute greatest common divisors and modular inverses, evaluate powers efficiently, and apply number theory to classical ciphers.
Analytical investigation means collecting an observation, identifying the mechanism, using a calculation or state trace to explain it, and checking your conclusion against evidence. Controlled comparison means changing one independent variable, holding the remaining relevant conditions constant, and measuring a dependent variable against a baseline. Experimental validation means comparing a predicted result to a reproducible observation or assertion; agreement inside a model does not certify hardware. Evidence-based reasoning connects a specific observation to a theoretical rule and states uncertainty, not merely an opinion. Performance characterization records a named metric and its units across conditions; sensitivity analysis changes one parameter across several values. A threat assessment links an asset, threat, consequence and evidence to a mitigation.
Experiment-specific guided practice
Objective: Compute greatest common divisors and modular inverses, evaluate powers efficiently, and apply number theory to classical ciphers.
Complete the analytical preparation below before programming. Show the intermediate mathematical calculations.
Euclidean and extended Euclidean algorithms — complete its numbered steps and record the requested evidence.
Totient and modular powers — complete its numbered steps and record the requested evidence.
Affine encryption and decryption — complete its numbered steps and record the requested evidence.
Reference check: gcd(12456,7272)=72; inverse(7,26)=15; the second Hill key has determinant 8 and is not invertible mod 26.
Model boundary: Fictional educational inputs. Browser algorithms and reference programs; no hardware or live-network measurements. Supplied starter notebooks may be incomplete; trace playback is recorded execution, not arbitrary Python running in browser.
Independent task and submission evidence
2. Euclidean and extended Euclidean algorithms — complete its numbered steps and record the requested evidence. Record the named input, prediction, actual output and one limitation; restore the original condition and repeat.
Before execution write the independent variable and its levels, dependent observation with units where applicable, baseline, controlled variables, measurement method and expected result. For a state machine use state/event/output rather than inventing a numeric metric. Record failures and repeat the baseline. A weak conclusion is “it works”; a supported conclusion names the changed setting, observed value/state, corresponding rule and one limitation.
Trial
Changed setting
Fixed settings
Predicted result
Actual observation / units
Evidence / uncertainty
A: baseline
Reference
Record
Predict
Record
Record
B: one change
Record
Same as A
Predict
Record
Record
A: repeat
Restore
Same as A
Predict
Record
Record
Completion: submit the filled table, relevant simulator screenshot or terminal/notebook output, reasoning with units/assumptions, and one limitation. Preserve the independent assessment questions; this guide does not fill their answers.
Scientific concepts and engineering principles
Scientific architecture · EC04 · Modular arithmetic II — Euclid, totient, Affine and Hill
Euclid reduces (a,b) to (b,a mod b) until the second operand is zero. Extended Euclid additionally computes integers s,t with sa+tb=gcd(a,b). The inverse of a modulo m exists exactly when gcd(a,m)=1; in that case s mod m is the inverse.
Totient and modular powers
For n>1 with distinct prime divisors p, φ(n)=n∏(1−1/p). Square-and-multiply evaluates a^e mod m while keeping intermediate values bounded. Euler’s theorem applies when gcd(a,m)=1; Fermat’s little theorem is its prime-modulus special case.
Affine and Hill ciphers
Affine encryption uses y=ax+b mod m. Hill encryption maps a column vector x to Kx mod m. Reversibility requires a unit multiplier or an invertible matrix; for a 2×2 key, gcd(det K,m)=1. A noninvertible key can produce forward outputs but cannot uniquely recover arbitrary inputs.
Prerequisites: EC03 and earlier foundations as applicable.
Algorithm structure and data flow. Use the simulation to inspect the corresponding numerical transformations.
Engineering diagrams
Remainders and Bézout coefficients underpin the inverse.
Scientific foundations and worked examples
Euclidean and extended Euclidean derivation
Repeated division gives 12456=1×7272+5184; 7272=1×5184+2088; 5184=2×2088+1008; 2088=2×1008+72; 1008=14×72. Thus gcd=72. Bézout coefficients satisfy sa+tb=gcd(a,b). For 7 and 26: 26=3×7+5, 7=5+2, 5=2×2+1; back substitution gives 1=3×26−11×7. The inverse is 15 modulo 26. An inverse of 8 modulo 26 does not exist.
Totient, modular powers and coprimality
For n=∏\(p_{i}\)^\(e_{i}\), φ(n)=n∏(1−1/\(p_{i}\)). For instance φ(24)=24(1−1/2)(1−1/3)=8. Repeated squaring gives powers using modular reduction at each multiplication: \(3^{2}\)≡2, \(3^{4}\)≡4, \(3^{8}\)≡2 modulo 7. If gcd(b,c)=1 and a|(b+c), any common prime divisor of a and b would also divide c, a contradiction; similarly for a and c. If each of a and b is coprime to c then their product is coprime to c.
Affine and Hill transformations
With A=0 and modulus 26, affine encryption is y=ax+b; inverse is x=\(a^{-1}\)(y−b). For a=5,b=2, \(a^{-1}\)=21. Hill encryption operates on column vectors y=Kx mod 26; the inverse is det(K)⁻¹ adj(K). The matrix [[3,4],[2,5]] has determinant 7, so it is invertible; [[4,2],[8,6]] has determinant 8 and is not invertible modulo 26. A successful forward multiplication does not prove that decryption is possible.
Engineering principles · additional worked teaching example
A modular inverse exists iff gcd(a,m)=1. For 7 mod26, 26=3×7+5,7=1×5+2,5=2×2+1; back-substitution yields 1=3×26−11×7, hence inverse15. Affine/Hill keys must be invertible in their modulus.
From theory to experiment
Predict the reference result before operating the workbench; check the actual intermediate state, units and constraints. The existing simulation, implementation and procedure below are distinct sources of evidence.
Worked engineering reasoning and boundary conditions
Euclid replaces (a,b) by (b,a mod b). An affine cipher needs gcd(a,26)=1; Hill matrices require invertible determinant. Example: 7·15=105≡1 mod 26.
Use the diagram to follow the calculation or state progression. Keep the teaching configuration separate from the independent exercise values; compare observations with the actual model and implementation.
Mathematical representation and interpretation
Bézout identity and modular inverse
The Euclidean divisions produce the gcd. Back-substitution yields integer coefficients x,y; x reduced modulo n gives the inverse if the gcd is one.
For 7 and 11: 11=7+4, 7=4+3, 4=3+1; 1=2(11)−3(7), so \(7^{-1}\)≡8 modulo 11.
Concept animation · operation pathway
Explore the teaching example independently of the simulator. Each step reveals an operation, data relationship or calculated state. The Simulation view has separate editable inputs.
Step 1 of 4 · Euclid
Euclid
Euclid
26=3×7+5
Continue
Euclid
26=3×7+5
Continue
7=1×5+2;5=2×2+1
Back-substitute
Euclid
26=3×7+5
Continue
7=1×5+2;5=2×2+1
Back-substitute
1=3×26−11×7
Normalize
Euclid
26=3×7+5
Continue
7=1×5+2;5=2×2+1
Back-substitute
1=3×26−11×7
Normalize
−11 mod 26=15
Teaching example only; inspect live calculations or real practical evidence separately.
Interactive flashcards
Self-rated study progress is stored locally, not used for official grades.
Browse all explanationsWhen does a modular inverse exist?
When gcd(a,m)=1.
What does Euclid compute?
The greatest common divisor by successive remainders.
When is an Affine key valid?
Its multiplier is invertible modulo alphabet size.
When can a Hill matrix be inverted?
Its determinant is a unit modulo the alphabet size.
What does Euclid's algorithm calculate?
The greatest common divisor using repeated remainders.
What is the inverse of 3 modulo 26?
9, because 3×9 ≡ 1 mod 26.
What does extended Euclid additionally return?
Coefficients satisfying ax+by=gcd(a,b).
What is Euler's totient of a prime p?
p−1.
What is φ(15)?
8.
Why use square-and-multiply?
It computes modular powers efficiently using exponent bits.
What condition must the Affine multiplier satisfy?
It must be coprime to the alphabet size.
When is a Hill matrix invertible modulo m?
When gcd(det(K),m)=1.
How do you verify a Hill inverse?
Multiply the matrices modulo m and obtain the identity matrix.
Find the inverse of 7 modulo 26.
7×15=105=4×26+1, so the inverse is 15.
Can the affine coefficient 13 be used with alphabet size 26?
Not for reversible encryption. gcd(13,26)=13; the map is not bijective.
A Hill matrix has determinant 2 modulo 26. Can it be inverted?
No. gcd(2,26)≠1. A modular inverse of the determinant does not exist.
Choose a workstation, edit the inputs, and observe recalculated results. Play or step through the actual calculation trace. Hash-search stations calculate successive candidates during playback. All inputs are fictional training data.
Where the browser requires Web Crypto, launch the local portal on localhost or use the HTTPS deployment. The classroom algorithms and keys are not intended for production use.
Independent theoretical exercises
Complete every question independently on paper or in the fields below before using the simulation or programming activities. Show formulas, intermediate steps, tables, proofs and units. Afterward verify your work using the simulator and Python, and explain discrepancies. Worked examples in Concepts do not replace your own derivation.
01 · Euclidean algorithm
Compute gcd(12456,7272). List every quotient and remainder.
Engineering method — A modular inverse exists iff gcd(a,m)=1. For 7 mod26, 26=3×7+5,7=1×5+2,5=2×2+1; back-substitution yields 1=3×26−11×7, hence inverse15. Affine/Hill keys must be invertible in their modulus. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
02 · Extended Euclid
Find the inverse of 7 modulo 26; investigate the inverse of 8 modulo 26. Show Bézout coefficients and existence conditions.
Engineering method — A modular inverse exists iff gcd(a,m)=1. For 7 mod26, 26=3×7+5,7=1×5+2,5=2×2+1; back-substitution yields 1=3×26−11×7, hence inverse15. Affine/Hill keys must be invertible in their modulus. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
03 · Euler totient
Calculate φ(17), φ(21), φ(24), φ(27), φ(29), φ(30), φ(36) using prime factorization.
Engineering method — A modular inverse exists iff gcd(a,m)=1. For 7 mod26, 26=3×7+5,7=1×5+2,5=2×2+1; back-substitution yields 1=3×26−11×7, hence inverse15. Affine/Hill keys must be invertible in their modulus. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
04 · Modular exponentiation
Calculate \(3^{8}\) mod 7, \(3^{25}\) mod 7 and \(5^{34}\) mod 24. Show modular reductions.
Engineering method — A modular inverse exists iff gcd(a,m)=1. For 7 mod26, 26=3×7+5,7=1×5+2,5=2×2+1; back-substitution yields 1=3×26−11×7, hence inverse15. Affine/Hill keys must be invertible in their modulus. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
05 · Affine encryption and decryption
With key (5,2), encrypt HELLO and decrypt GFLB using A=0. Show each modular step.
Engineering method — A modular inverse exists iff gcd(a,m)=1. For 7 mod26, 26=3×7+5,7=1×5+2,5=2×2+1; back-substitution yields 1=3×26−11×7, hence inverse15. Affine/Hill keys must be invertible in their modulus. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
06 · Hill cipher I
Using K=[[3,4],[2,5]], calculate the determinant and modular inverse, encrypt WORD and decrypt MIUA.
Engineering method — A modular inverse exists iff gcd(a,m)=1. For 7 mod26, 26=3×7+5,7=1×5+2,5=2×2+1; back-substitution yields 1=3×26−11×7, hence inverse15. Affine/Hill keys must be invertible in their modulus. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
07 · Hill cipher II
Using K=[[4,2],[8,6]], encrypt MORE; investigate whether JDKX can be uniquely decrypted. Explain the determinant condition instead of assuming an inverse exists.
Engineering method — A modular inverse exists iff gcd(a,m)=1. For 7 mod26, 26=3×7+5,7=1×5+2,5=2×2+1; back-substitution yields 1=3×26−11×7, hence inverse15. Affine/Hill keys must be invertible in their modulus. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
08 · Coprimality proofs
For positive a,b,c: prove that a|(b+c) and gcd(b,c)=1 imply gcd(a,b)=gcd(a,c)=1. Then prove that gcd(a,c)=gcd(b,c)=1 implies gcd(ab,c)=1.
Engineering method — A modular inverse exists iff gcd(a,m)=1. For 7 mod26, 26=3×7+5,7=1×5+2,5=2×2+1; back-substitution yields 1=3×26−11×7, hence inverse15. Affine/Hill keys must be invertible in their modulus. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
09 · Derivation
Derivation · Independent work
Use EEA to find inverse of 11 modulo 26; explain why multiplier 13 is invalid for affine encryption.
Derivation — A modular inverse exists iff gcd(a,m)=1. For 7 mod26, 26=3×7+5,7=1×5+2,5=2×2+1; back-substitution yields 1=3×26−11×7, hence inverse15. Affine/Hill keys must be invertible in their modulus. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
Responses are saved locally when browser storage is available. Export your work for submission. No automatic grading or remote upload occurs.
Expanded independent theoretical exercise bank
Progress from calculation and interpretation to diagnosis and controlled engineering design. Complete the questions without opening the simulation first; show intermediate steps.
Foundational · Apply the principle
Independent theoretical exercise · EC04-01
Find gcd(84,30) with divisions.
Intermediate · Calculate or trace
Independent theoretical exercise · EC04-02
Find inverse 9 mod 26.
Intermediate · Interpret the result
Independent theoretical exercise · EC04-03
Compute φ(15) and list coprime residues.
Advanced · Analyze a condition
Independent theoretical exercise · EC04-04
Encrypt H (7) with affine a=5,b=8.
Advanced · Diagnose or compare
Independent theoretical exercise · EC04-05
Is a=13 valid for affine modulo 26? Give a collision.
Challenging · Engineering verification
Independent theoretical exercise · EC04-06
Is matrix [[2,1],[0,3]] invertible modulo 26?
Activity sequence
Follow the setup commands, then each named activity. The detailed instructions, given values and recording fields appear below.
Complete the analytical preparation below before programming. Show the intermediate mathematical calculations.
Coprimality proofs — complete its numbered steps and record the requested evidence.
Compare observations with the reference checks and submit the required evidence.
Analytical preparation — before Python
Complete this written or hand-calculation activity first, then compare it with the simulator and executable implementation.
Write every Euclidean quotient and Bézout step for the assigned numbers. Calculate the totients by prime factors and determine the invertibility of both Hill matrices before attempting decryption.
Evidence: show the derivation, intermediate values and independent checks; explain any mismatch with the practical result.
Practical laboratory manual
Scientific experimental protocol
Research question: Which arithmetic conditions permit inversion and reversible classical encryption?
Hold modulus and plaintext fixed while varying key; compare valid and non-invertible cases.
Validation and evidence
Before running a trial, predict its output. Use the baseline conditions below to check your method, then vary one independent variable. Save calculated outputs or the actual Python trace. Keep browser results and local Python execution distinct.
Trial
Controlled configuration
Reference check
Student observation (editable)
Euclid
12456, 7272
GCD 72; verify the Bézout identity
Enter observation
Inverse
7 mod 26; 8 mod 26
15; no inverse for 8
Enter observation
Hill
Invertible matrix versus determinant sharing a factor with 26
Correct recovery only for invertible key
Enter observation
Analysis: Validate each inverse by multiplication. For Hill, distinguish matrix orientation and alphabet length before comparing a ciphertext.
Compute greatest common divisors and modular inverses, evaluate powers efficiently, and apply number theory to classical ciphers.
Equipment and execution
Browser-based simulator, Python 3, notebook or local evidence folder. Use WSL Setup only if you need a Linux runtime.
2. Follow these commands in sequence (Linux/WSL). For browser-only activities, open Simulation first; the code activities are independent.
BASH · Command
cd code
python lab04.py
3. Run the check before changing inputs. Record the exact Python version and any dependency error. Use Python visualizer to inspect the recorded traces; for edited code, generate and import a new trace using the instructions in that tab.
Complete the activities in order. Hold the controlled conditions fixed, record the input and actual output, and compare your observations with an independent calculation or test vector.
01
Euclidean and extended Euclidean algorithms
Open the exact workstation
Choose the relevant tab below, enter the assigned values in the activity steps, then use Step or Play to inspect intermediate calculations. Return to Experiment and record the results before changing the input.
Reproduce the worked division trace for 662 and 414, then compute gcd(12456,7272) by repeated division.
Record quotient, remainder and Bézout coefficients at each row; verify sa+tb=gcd.
Compute \(7^{-1}\) mod 26 and test \(8^{-1}\) mod 26. Explain rejection of a nonunit.
Evidence to record
Division table, identity, valid inverse and invalid case.
Verification: Record the baseline and modified input separately, note the observed intermediate values, compare with the assigned calculation, and explain any mismatch. Do not replace observations with expected values.
02
Totient and modular powers
Open the exact workstation
Choose the relevant tab below, enter the assigned values in the activity steps, then use Step or Play to inspect intermediate calculations. Return to Experiment and record the results before changing the input.
List coprime residues for 12 and 6 , then compute φ(17), φ(21), φ(24), φ(27), φ(29), φ(30), φ(36) using factorization.
Evaluate \(3^{8}\) mod 7, \(3^{25}\) mod 7 and \(5^{34}\) mod 24 by repeated squaring; compare with Fermat/Euler only when their hypotheses hold.
Evidence to record
Seven totients, exponentiation traces and theorem conditions.
Verification: Record the baseline and modified input separately, note the observed intermediate values, compare with the assigned calculation, and explain any mismatch. Do not replace observations with expected values.
03
Affine encryption and decryption
Open the exact workstation
Choose the relevant tab below, enter the assigned values in the activity steps, then use Step or Play to inspect intermediate calculations. Return to Experiment and record the results before changing the input.
Map A=0…Z=25. Use key (5,2) to encrypt HELLO by y=(5x+2) mod 26.
Compute the multiplicative inverse of 5 modulo 26 and decrypt GFLB. Verify by re-encryption.
Evidence to record
Character index table, ciphertext and recovered text.
Verification: Record the baseline and modified input separately, note the observed intermediate values, compare with the assigned calculation, and explain any mismatch. Do not replace observations with expected values.
04
Hill matrices and invertibility
Open the exact workstation
Choose the relevant tab below, enter the assigned values in the activity steps, then use Step or Play to inspect intermediate calculations. Return to Experiment and record the results before changing the input.
Use column digraphs, K=[[3,4],[2,5]], modulus 26; compute determinant, its modular inverse if it exists, then encrypt WORD and decrypt MIUA.
Repeat with K=[[4,2],[8,6]]: encrypt MORE as a forward matrix transform if instructed, then attempt to decrypt JDKX. Distinguish a noninvertible transformation from a usable cipher key.
If the simulator refuses an invalid key, record the rejection and perform the forward matrix multiplication separately.
Evidence to record
Matrices, determinant, products and recovery or mathematical rejection.
Verification: Record the baseline and modified input separately, note the observed intermediate values, compare with the assigned calculation, and explain any mismatch. Do not replace observations with expected values.
05
Coprimality proofs
Open the exact workstation
Choose the relevant tab below, enter the assigned values in the activity steps, then use Step or Play to inspect intermediate calculations. Return to Experiment and record the results before changing the input.
Prove the implication a|(b+c), gcd(b,c)=1 ⇒ gcd(a,b)=gcd(a,c)=1.
Prove gcd(a,c)=gcd(b,c)=1 ⇒ gcd(ab,c)=1 using common prime divisors or Bézout.
Evidence to record
Two proofs; finite numerical checks alone are not sufficient.
Verification: Record the baseline and modified input separately, note the observed intermediate values, compare with the assigned calculation, and explain any mismatch. Do not replace observations with expected values.
Verification criteria
gcd(12456,7272)=72; inverse(7,26)=15; the second Hill key has determinant 8 and is not invertible mod 26.
Deliverables
Submit Euclid traces, inverse decisions, seven totient values, power traces and Affine/Hill encrypt/decrypt results.
Download this notebook and open Google Colab. Select File → Upload notebook and choose the downloaded .ipynb.
Read the Markdown instructions before each executable cell. Use a Python runtime, run cells from top to bottom, and resolve imports if necessary.
Perform the baseline and controlled changes. Save the notebook with actual outputs and your written interpretation.
Execution scope: Fictional educational inputs. Browser algorithms and reference programs; no hardware or live-network measurements. Supplied starter notebooks may be incomplete; trace playback is recorded execution, not arbitrary Python running in browser. Default computational cells passed isolated local Python execution; physical equipment and live services require separate verification.
01Instructions · Markdown
# EC04 · Modular arithmetic II — Euclid, totient, Affine and Hill
**PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh**
## 1. Scientific objective
Follow the setup commands, then each named activity. The detailed instructions, given values and recording fields appear below.
Complete the analytical worksheet in the portal first. Record your predictions before running this notebook. This notebook is a bounded local computational investigation; use the portal’s separate WSL, hardware or Remix procedure for real interfaces.
02Instructions · Markdown
## Experiment-specific preparation
Compute greatest common divisors and modular inverses, evaluate powers efficiently, and apply number theory to classical ciphers.
**Reference procedure (use the matching simulator/WSL tool where named, not an unrelated service):**
1. Complete the analytical preparation below before programming. Show the intermediate mathematical calculations.
2. Euclidean and extended Euclidean algorithms — complete its numbered steps and record the requested evidence.
3. Totient and modular powers — complete its numbered steps and record the requested evidence.
4. Affine encryption and decryption — complete its numbered steps and record the requested evidence.
5. Hill matrices and invertibility — complete its numbered steps and record the requested evidence.
**Evidence:** gcd(12456,7272)=72; inverse(7,26)=15; the second Hill key has determinant 8 and is not invertible mod 26.
**Boundary:** Fictional educational inputs. Browser algorithms and reference programs; no hardware or live-network measurements. Supplied starter notebooks may be incomplete; trace playback is recorded execution, not arbitrary Python running in browser.
03Instructions · Markdown
## 2. Reference configuration and investigation
1. Complete the analytical preparation below before programming. Show the intermediate mathematical calculations.
2. Euclidean and extended Euclidean algorithms — complete its numbered steps and record the requested evidence.
3. Totient and modular powers — complete its numbered steps and record the requested evidence.
4. Affine encryption and decryption — complete its numbered steps and record the requested evidence.
5. Hill matrices and invertibility — complete its numbered steps and record the requested evidence.
6. Coprimality proofs — complete its numbered steps and record the requested evidence.
7. Compare observations with the reference checks and submit the required evidence.
Run cells in order; do not substitute model results for physical measurements.
04Instructions · Markdown
## 3. Algorithm implementation
Read each definition and relate it to the equations and scientific SVGs in Concepts.
05Instructions · Markdown
### Implementation cell 1
Inspect the definitions, then execute to make them available for the investigation.
06Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC04 | Code cell 01 | Modular arithmetic II — Euclid, totient, Affine and Hill
# Purpose: Implementation cell 1 Inspect the definitions, then execute to make them available for the investigation.
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
"""Essential 04 — Euclid, totient, Affine and Hill cipher primitives."""
from math import gcd
from string import ascii_uppercase as A
# Define the reusable operation extendedGCD; keep its logic separate from the trial.
def extendedGCD(a,b):
x,y,u,v=1,0,0,1
while b:
q,r=divmod(a,b); a,b=b,r; x,u=u,x-q*u; y,v=v,y-q*v
return (a,x,y) if a>=0 else (-a,-x,-y)
### Implementation cell 2
Inspect the definitions, then execute to make them available for the investigation.
08Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC04 | Code cell 02 | Modular arithmetic II — Euclid, totient, Affine and Hill
# Purpose: Implementation cell 2 Inspect the definitions, then execute to make them available for the investigation.
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Define the reusable operation inverseMod; keep its logic separate from the trial.
def inverseMod(a,m):
if m<2: raise ValueError('Modulus must exceed one')
d,s,_=extendedGCD(a,m)
if d!=1: raise ValueError('No modular inverse')
return s%m
# Define the reusable operation primeFactors; keep its logic separate from the trial.
def primeFactors(n):
if n<2: raise ValueError('n must be ≥2')
result=[]; d=2
while d*d<=n:
while n%d==0: result.append(d); n//=d
d+=1
if n>1: result.append(n)
return result
# Define the reusable operation eulerTotient; keep its logic separate from the trial.
def eulerTotient(n):
result=n
for p in set(primeFactors(n)): result=result//p*(p-1)
return result
### Implementation cell 3
Inspect the definitions, then execute to make them available for the investigation.
10Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC04 | Code cell 03 | Modular arithmetic II — Euclid, totient, Affine and Hill
# Purpose: Implementation cell 3 Inspect the definitions, then execute to make them available for the investigation.
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Define the reusable operation sqm; keep its logic separate from the trial.
def sqm(a,e,m):
if e<0 or m<2: raise ValueError('Invalid exponent or modulus')
value=1; a%=m
while e:
if e&1: value=value*a%m
a=a*a%m; e//=2
return value
# Define the reusable operation affine; keep its logic separate from the trial.
def affine(text,a,b,decrypt=False):
inverse=inverseMod(a,26)
return ''.join(A[(inverse*(A.index(c)-b) if decrypt else a*A.index(c)+b)%26] for c in text.upper() if c in A)
# Define the reusable operation inverseMatrixMod; keep its logic separate from the trial.
def inverseMatrixMod(k,m):
a,b=k[0]; c,d=k[1]; z=inverseMod(a*d-b*c,m)
return [[d*z%m,-b*z%m],[-c*z%m,a*z%m]]
### Implementation cell 4
Inspect the definitions, then execute to make them available for the investigation.
12Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC04 | Code cell 04 | Modular arithmetic II — Euclid, totient, Affine and Hill
# Purpose: Implementation cell 4 Inspect the definitions, then execute to make them available for the investigation.
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Define the reusable operation hill; keep its logic separate from the trial.
def hill(text,k,alphabet=A,decrypt=False):
m=len(alphabet); inv=inverseMatrixMod(k,m); k=inv if decrypt else k
text=''.join(c for c in text.upper() if c in alphabet)
if len(text)%2:
if decrypt: raise ValueError('Odd ciphertext length')
text+='X'
out=[]
for i in range(0,len(text),2):
x,y=map(alphabet.index,text[i:i+2]); out.extend(alphabet[(r[0]*x+r[1]*y)%m] for r in k)
return ''.join(out)
## 4. Execute reference controls
The program checks selected algorithm outcomes. Record the observed output. These checks do not replace the independent calculation assignment.
14Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC04 | Code cell 05 | Modular arithmetic II — Euclid, totient, Affine and Hill
# Purpose: 4. Execute reference controls The program checks selected algorithm outcomes. Record the observed output. These checks do not replace the independent calculation assignment.
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert extendedGCD(12456, 7272)[0] == 72 and inverseMod(7, 26) == 15
try:
inverseMod(8, 26)
except ValueError:
pass
else:
raise AssertionError('Invalid inverse accepted')
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert eulerTotient(24) == 8 and sqm(5, 34, 24) == pow(5, 34, 24)
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert affine(affine('HELLO', 5, 2), 5, 2, True) == 'HELLO'
# Set k for the next computation or reference condition.
k = [[3, 4], [2, 5]]
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert hill(hill('WORD', k), k, decrypt=True) == 'WORD'
print('Euclid, inverse, powers and cipher tests passed')
## 5. Controlled variation
Predict the effect of the parameter changes below. Compare each actual result to your prediction.
16Python · executable cell
PYTHON · Code cell
# =====================================================================
# EC04 | Code cell 06 | Modular arithmetic II — Euclid, totient, Affine and Hill
# Purpose: 5. Controlled variation Predict the effect of the parameter changes below. Compare each actual result to your prediction.
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
# Repeat the same operation for each configured input so observations are comparable.
for a in (5,7,11):
print(a,gcd(a,1980))
## Experimental analysis and submission
1. Record the reference input, predicted output and actual result.
2. Modify one independent variable and run the relevant cells again.
3. Explain the result using the theory and identify model limitations.
4. Save the notebook with outputs and retain the separate theoretical worksheet.
**Your derivation and conclusion:**
(Complete independently.)
18Instructions · Markdown
## Guided reasoning and evidence
A controlled comparison changes one independent input while keeping the other relevant inputs fixed; the dependent variable is the recorded output. Use this lab’s reference condition above.
**Independent task:** 2. Euclidean and extended Euclidean algorithms — complete its numbered steps and record the requested evidence. Record the named input, prediction, actual output and one limitation; restore the original condition and repeat.
| Trial | Input/configuration | Prediction | Observation | Evidence / limitation |
|---|---|---|---|---|
| A | Reference | | | |
| B | Changed input | | | |
| A repeat | Reference | | | |
A conclusion is supported only when it cites the recorded values or observed states and explains them with the experiment theory.
Python implementation
Download the complete practical toolkit and extract it to a new directory. Keep the code and challenges folders together.
Explore actual CPython execution traces from the included laboratory programs. Play, pause, step, inspect the current line, local variable values, function call stack, return values and output. Green variable cells changed relative to the preceding event. Line events show state before the highlighted line executes.
Run and visualize your own modified Python program
Download the Essential Cryptography Toolkit, extract it, and open a terminal in its code directory. Run the worked example or edit a copy. The trace generator executes your actual local Python file and creates an importable JSON record. Only run trusted code and use fictional keys and data.
Choose Import your trace in the visualizer and select my-trace.json. This works offline; the portal does not execute arbitrary Python on its server. The optional external Python Tutor link is suitable for standalone standard-library code, but external dependencies or local imports may not work.
For AES/DES exercises, install either supported cryptographic backend in an isolated Python environment as described in the Python code tab. Native library internals are not traced; the algorithm-specific browser workstations display the intermediate mathematics.
Why do some matrices fail despite being nonsingular over the real numbers?
How does square-and-multiply avoid huge integers?
Submission: Submit Euclid traces, inverse decisions, seven totient values, power traces and Affine/Hill encrypt/decrypt results.
Export actual calculated observations from each workstation. Record your own predictions and conclusions, and distinguish browser calculations from local or physical measurements.
Shared research workbenches · network designer & advanced studiesConcurrent-device simulation & Monte Carlo research