gold 7/15/2026. Advisor and discussion has requested snippets on Simulation for Shor's Algorithm. Also, what are performance and computation times between Classical and Quantum algorithms in idealized set up? The simulation model is intended as an exploratory framework for TCL/TK coding. The full up Shor's algorithm is normally run on Quantum computers using Quantum feasible languages. Task Statement: generate a tutorial simulation of Shor's algorithm for a classical computer in pure TCL 8.6+. Adding references to Dr. Chiara Marletto's counterfactual framework from the book "The Science of Can and Can't" along with other perspectives. We are using modular snippets inside modular structured programs. Page content is targeted for engineering students and other Quantum tutorials.
gold 7/15/2026. Upon review of draft page, First Advisor ....
I do not have all the answers. The Ideas Seemed to work, but maybe drawbacks? When measured by the Tcl timing statements, completion times and solutions of parameters will differ on different computer set-ups. Assume a future maintainer, either AI Model or human programmer, would have to maintain code with info content and explanatory variable name in program, ref "Snippets Concepts Effects". The Nassi Shneiderman Diagrams NSD or psuedocode Flowcharts pertain to the Tool Control Language TCL computer language as well as other computer languages like Python 3, pseudocode, word logic problems, and technical reports.
For each logic condition selecting a path or calculation task, we might have one, two, or multiple deterministic branches. Attempting to adapt format to multiple probabilistic branches used in Artificial Intelligence AI Models. Then we may use the >>> lottery algorithm <<< to select the winning pathways or tickets.
The existing program has some dummy subroutines. A full construction seems too complex here. I found a paper with images of quantum walks, and I’m wondering if it’s possible to simulate the curves shown in the charts. My advisor has suggested that quantum entanglement/superposition could simulate or underlie quantum worlds, but I’m not sure that I agree. I have limited space on the wiki page, and the fill‑in for the dummy routines has to be pretty brief. In engineering terms, I’m aiming for a “90% solution”, meaning about 90% right and 10% off. Like the simple college formula for a pendulum that is not the exact time series. Call it “fake it ’til you make it” as a college try, but for Quantum Many Worlds. Who is to say? Perhaps you know, TcL specializes in GUI solutions. Maybe try and adapt some starter TcL code for a "quantum worlds slide rule ". Hopefully compatible with the hard-wired classical theory.
The TCL Snippets illustrate ideal mathematical behavior only and do not perform full simulation, actual measurements, or state vector evolution. The tool only visualizes ideal math structure, whereas no state vector simulation, probabilities, or actual measurement outcomes are derived. This tool for visualization does not simulate actual measurement outcomes or state vector evolution during operations. These are idealized protocols for tutorial purposes. Primarily, TCL /TK uses its strong points here for book keeping and displays. The example tool is not a full emulator. Meaning, limited scope for tutorial purposes.
Disclaimer. None of the computer programs, numerical experiments, power-law fits, or physical analogies described here give a strict, formal proof of the Conjectures, either individually or in combination. The tools and analogies are heuristic models and visualization tools that follow engineering “rules of thumb.” Whereas, pure mathematics has its own shop rules for what counts as a rigorous proof. Any opinions on the difficulty or plausibility reflect current understanding here and programming of the Conjectures as a very hard open problem, not a completed exact math proof, and are offered with full respect for the standards of professional mathematicians.
In debugging the calculations, some of the printout values reflect roughly 17-digit precision output from a typical double-precision computation. It's not "true exact" beyond 5 significant figures. Extra significant figures are used to check the calculations from other computer set-ups, not necessarily to infer accuracy of data measurements here. Typically, the slight differences in decimal places on far right of decimal point are normal floating-point behavior in Tcl's expr.
gold 7/15/2026. There are different methods for factoring numbers the usual way. All the methods all take costly time. Quantum computers can handle factoring in polynomial time though. Shor's algorithm is what makes it work. Shor's algorithm has quite a few stages. Most parts of the Algorithm run fine on a normal computer. The period finding part is the one that stays slow, if without quantum hardware and quantum coding. Only a quantum computer can do that period finding efficiently.
For learning purposes, a simulation of Shor's Algorithm still works on a classical computer, meaning a Windows 11 laptop. The time and speed take a hit. But I think it gets the idea and concepts across. Some parts may feel a bit slow when you try the simulation that way.
Quantum simulation on a classical computer is about emulating the math of a quantum system or circuit with regular hardware. The basic idea here is that the machine works out how states change over time along with probabilities and measurements.
You handle this by manipulating vectors and matrices that represent the qubits. Tensor networks can come up too depending on the setup. It seems straightforward at first but I am not totally sure how it scales when things get bigger.
Note. The term Marletto Counterfactual refers to the nuanced definitions from the recent Marletto papers. There may be differences in evolving definitions from other previous or contemporary writers.
Clarifying the "Oracle" Concept. Many people become confused when they hear the word Oracle in quantum computing. Many assume that the Oracle is a purely quantum routine that only runs on a real quantum computer. In Qiskit and most quantum SDKs, the Oracle is almost always a classical function written in Python. Meaning, Python that runs on a normal classical computer.
Detailed: Qiskit code runs on classical hardware unless a quantum backend is explicitly used. Oracle like subcircuits can appear in both Grover and Shor Algorithms. But typically, Grover uses an obvious Oracle Function. Some later implementations of Shor may hide that same idea inside other circuit components, and maybe unnamed in the code.
I use simple word problems or models as preparation for coding. The following counterfactual examples were developed for TCL coding. The word problems or models draw inspiration from the constructor theory framework of Dr. David Deutsch and Dr. Chiara Marletto.
1. Classical Factoring
2. Period Finding
3. Quantum Speedup
4. Random Base Selection
5. Simulation Limit
On Quantum Computation Limits ..... “The theory (Constructor Theory) can express statements about which tasks are possible and which are impossible, even when we do not have a full dynamical description.” — Chiara Marletto, The Science of Can and Can't
6. Reasonable Conclusions from Word Problems.
“Is efficient factoring possible?” → Yes on quantum hardware “Is efficient factoring possible?” → No on classical hardware
The word problems or models draw inspiration from the constructor theory framework of Dr. David Deutsch and Dr. Chiara Marletto.
Constructor Theory says some tasks are truly impossible. Engineers say: “Let’s test that.”
With a million trials, the standard Monte Carlo Pi algorithm usually gets you about two or three correct decimal places on a classical computer. That’s not super precise, and honestly, Monte Carlo isn’t known for being efficient. Still, if you’re just diving into quantum algorithms, there are a few broad similarities between Monte Carlo and famous Quantum Algorithms like Grover’s or Shor’s.
The Monte Carlo methods rely on random sampling in classical computing. The Monte Carlo PI algorithm just tosses lots of random guesses and checks what sticks to the target circle. Quantum algorithms, though, use interference and other Quantum implementations, so Quantum Algorithms can get meaningful results with far fewer steps. But from a beginner’s perspective, there’s actually one interesting overlap. These algorithms, classical and quantum, work by exploring lots of possibilities. Then somehow amplify or pick out the useful throws or solutions that matter. All three algorithms involve the idea of “trying many possibilities” and then selecting or amplifying the good solutions. The main difference is that the quantum algorithms here use interference to dramatically reduce the number of trials needed.
That is why a toy model is educationally valuable. Toy models help beginners see the spirit of what quantum algorithms do, even if it’s not the real thing.
Different Monte Carlo PI algorithms give different PI distributions of random base points. The plain Monte Carlo PI might be considered the initial distribution. The Weighted Monte Carlo PI is effectively Monte Carlo PI with a weighting system. There is a different point distribution in thre Weighted Monte Carlo PI. In loose terms, Monte Carlo PI works like throwing darts on a circular dart board. Like the game of Darts, only the distribution of more darts inside the circle will give a better score. In my understanding, if there are more points or meat inside the circle, the algorithm is better performance. Extension would be switches to select the plain, weighted, or various experiments.
Discussing an analogy here.
Classical dart simulation in the Monte Carlo PI Algorithm offers a familiar picture or analogy. A person throws one dart at a time into a square that contains a quarter circle. The computer checks whether each dart lands inside the curved region. The estimate of the mathematical constant PI improves slowly because the error decreases only like the square root of the number of throws. A run of E4 classical throws gives a reasonable estimate, but a run of one million E6 throws is needed to reduce the error by a factor of one thousand E3. A classical laptop can perform this task easily, but the improvement remains gradual.
Quantum dart simulation uses a very different idea. A quantum computer prepares a special quantum state that represents many possible dart positions at once. This state is called a superposition. The quantum algorithm does not simulate thousands of separate throws. Instead, the algorithm amplifies the probability of positions that fall inside the quarter circle. This process is known as Quantum Amplitude Estimation QAE. A sequence of carefully chosen Grover iterations increases the weight of the correct outcomes. A run of roughly one thousand Grover iterations can reach an accuracy similar to one million classical throws. This difference illustrates the quadratic speedup that makes quantum methods attractive.
Quantum operations remain difficult today. A quantum circuit requires stable qubits, precise timing, and careful error control. A small demonstration can succeed in a laboratory, but a large simulation remains out of reach. Future quantum machines may change this situation. Faster estimation of areas and probabilities could improve scientific modeling, financial risk analysis, and engineering design. A practical example would be a quantum routine that estimates the value of an integral in physics with far fewer steps than a classical Monte Carlo method.
In summary, classical darts rely on simple sequential sampling, while quantum darts rely on parallel exploration and probability amplification. Classical methods remain easy to use but slow to improve. Quantum methods promise dramatic gains in accuracy but remain challenging to implement with current technology.
I am getting many requests for quantum analogies from off site queries. Which is striking turn around for a pragmatic engineer. I am more a cloud of fuzzy ideas than the Rainbows of Wisdom. Joke!
Quantum superposition can be pictured through a spinning coin. A coin that spins in the air does not sit in a clear heads state or a clear tails state. The coin exists in a cloud of both possibilities until the coin lands. A quantum bit behaves in a similar way, except the cloud can contain many possibilities at once. A simple example appears in a quantum circuit that prepares a qubit in a mixture of zero and one until a measurement occurs. Readers who want more detail can explore Quantum Superposition.
Measurement creates a sudden change. The spinning coin lands and becomes either heads or tails. A quantum bit behaves in the same way when a measurement occurs. The cloud of possibilities collapses into one definite value. A classroom demonstration often uses a light sensor that reads a qubit and forces the qubit into a single state. Readers who want more detail can explore Quantum Measurement.
Quantum Entanglement can be pictured through a pair of magic dice. Each die always shows the same number even when the dice sit far apart. A pair of entangled quantum bits behaves in a similar way. The state of one quantum bit determines the state of the other quantum bit even when the two quantum bits sit in distant locations. A simple example appears in a Bell pair created in an introductory quantum computing class. Readers who want more detail can explore Quantum Entanglement.
Quantum interference resembles waves in a pond. Two waves can meet and create a larger wave or a smaller wave. A quantum algorithm uses this idea to strengthen correct answers and weaken incorrect answers. A simple example appears in a search routine that increases the chance of finding the correct item in a list. Readers who want more detail can explore Quantum Interference.
Amplitude estimation can be pictured through quantum darts. A classical computer throws one dart at a time and counts how many darts land inside a circle. A quantum computer creates a cloud containing all possible dart positions at once. The quantum computer then amplifies the part of the cloud that lies inside the circle. This process allows the quantum computer to estimate the area with far fewer steps than a classical method. Readers who want more detail can explore Quantum Amplitude Estimation QAE.
Real computer hardware has noise, error correction overhead, and implementation costs. The estimates are idealized setups for tutorial purposes, not final engineering estimates. Estimates are based on idealized toy models.
These are approximate estimates for Standard Monte Carlo Pi on Classical Computer. Classical Monte Carlo error scales like error =~ 1 / SQRT(N) in ideal toy model. Quantum amplitude estimation QAE error scale =~ 1 / N in an ideal toy model.
Problem 1 Given N = 10^4 classical trials, find the error scale. Calculation: error = 1 / sqrt(N) = 1 / sqrt(10^4) = 1 / 10^2 = 10^-2. Answer: Error is about 0.01, which gives 2 decimal places. Problem 2 Given N = 10^6 classical trials, find the error scale. Calculation: error = 1 / sqrt(10^6) = 1 / 10^3 = 10^-3. Answer: Error is about 0.001, which gives 3 decimal places. Problem 3 Given N = 10^2 classical trials, find the error scale. Calculation: error = 1 / sqrt(10^2) = 1 / 10 = 10^-1. Answer: Error is about 0.1, which gives 1 decimal place. Problem 4 Given N = 10^8 classical trials, find the error scale. Calculation: error = 1 / sqrt(10^8) = 1 / 10^4 = 10^-4. Answer: Error is about 0.0001, which gives 4 decimal places.
These are approximate for Standard Monte Carlo Pi. Approximate Symbol is =~ here. Quantum amplitude estimation QAE error scale =~ 1 / N in an ideal toy model. Quantum Computer might use QAE for a different PI algorithm. These are assessments from Toy Models.
Problem 5 Given N = 10^3 quantum trials, find the error scale using 1/N. Calculation: error = 1 / 10^3 = 10^-3. Answer: Error is about 0.001, which gives 3 decimal places. Problem 6 Given N = 10^5 quantum trials, find the error scale. Calculation: error = 1 / 10^5 = 10^-5. Answer: Error is about 0.00001, which gives 5 decimal places. Problem 7 Find N for quantum method to achieve error 10^-4. Calculation: 1 / N = 10^-4, so N = 10^4. Answer: 10,000 trials. Problem 8 Compare classical and quantum trials for error 10^-3. Calculation: classical needs N = 10^6, quantum needs N = 10^3. Answer: Quantum uses 1,000 times fewer trials.
Approximate Symbol is =~ here. Quantum amplitude estimation QAE error scale =~ 1 / N in an ideal toy model. Quantum Computer might use QAE for a different PI algorithm. These are assessments from Toy Models.
Problem If each trial takes 1 microsecond, compute time for N = 10^6. Calculation: time = 10^6 microseconds = 1 second. Answer: About 1 second. Problem If each trial takes 1 microsecond, compute time for N = 10^10. Calculation: 10^10 microseconds = 10^4 seconds, which is about 2.78 hours. Answer: About 2.78 hours. Problem If quantum method uses N = 10^5 trials at 1 microsecond each. Calculation: time = 10^5 microseconds = 0.1 seconds. Answer: About 0.1 seconds. Problem If classical system runs 10^8 trials per second, compute time for N = 10^12. Calculation: time = 10^12 / 10^8 = 10^4 seconds, about 2.78 hours. Answer: About 2.78 hours. Problem If quantum system runs 10^6 trials per second for N = 10^6. Calculation: time = 10^6 / 10^6 = 1 second. Answer: About 1 second.
Mapping for Version V5:
Quantum simulation on a classical computer is basically doing the tasks or math for how a quantum system would behave but on normal hardware. A classical machine has to work out all the changes in the states and probabilities and what measurements would give by handling vectors and matrices that stand for the qubits. Classical quantum simulation is essential for:
Typically, Classical computers need many more trials and much computer time to gain extra decimal places of accuracy. While some Quantum algorithms or Quantum amplitude estimation QAE can reduce the trial count much faster in idealized settings, meaning a Quantum Computer. For tutorial purposes, TCL/TK coding can be used to model or simulate those portions or stages of a Quantum Algorithm that may use a classical computer.
This sort of a 1:1 on constructor engine points to modules of Shor's Algorithm.
| Index | Aspect | Full Dynamical Description | High-Level (Constructor Theory Style) | What We Actually Use for Shor’s | Quibble Notes |
|---|---|---|---|---|---|
| 1 | Quantum Gates | Extremely complex wavefunction evolution | "This transformation is possible" | High-level circuit model | Standard abstraction used in practice |
| 2 | Period Finding | Huge number of quantum states evolving | "Efficient period finding is possible" | Quantum Fourier Transform | Core quantum advantage |
| 3 | Factoring Large Numbers | Unknown exact path for best classical method | "Fast factoring is impossible classically" | Complexity theory + quantum | No efficient classical algorithm known |
| 4 | Overall Algorithm | Infeasible to write full equations | Marletto Counterfactual: possible on quantum, impossible classically | Abstract circuit model | Higher-level description sufficient |
| AUDIT Window | 4 rows processed | Content verified | Consistent with Constructor Theory | Good coverage of key ideas |
Note. The term Marletto Counterfactual refers to the nuanced definitions from the recent Marletto papers, 2025+. There may be differences in evolving definitions from other previous or contemporary writers.
Note. TCL Wiki has numerous excellent pages on Monte Carlo methods, largely from arjen .
These Approximation tables and simple formulas are used to scope out the algorithm for possible solutions. Standard Monte Carlo Pi Algorithm with 1 million trials gives ~2–3 decimal places. May not have right terms. There appears to be slow octane, medium octane or fast octane paths for a quantum algorithm solution. Maybe depends on Quantum algorithms, problem type, token economics, or "implementation = hardware" terms.
| Index | Desired PI Accuracy | Classical Trials | Simulation Interference Trials | Slow Quantum Path | Medium Octane Quantum | Fast Octane Quantum | Abbrev. Quantum Alg | Abbrev. Classical Alg | Quibble Notes |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 3 decimals | ~10,000,000 | ~1,000,000 | ~100,000 | ~10,000 | ~3,000 | QAE / Grover | Monte Carlo | Noticeable improvement |
| 2 | 5 decimals | ~1,000,000,000 | ~100,000,000 | ~10,000,000 | ~300,000 | ~100,000 | QAE | Monte Carlo | Strong improvement |
| 3 | 8 decimals | huge (10^16+) | large (10^14+) | manageable | ~10 million | ~ few million | Amplitude Estimation | Standard MC | Fast octane needs large QC |
| 4 | 10+ decimals | impractical | very slow | difficult | hard | feasible on big QC | QAE / Shor-style | Classical MC | Exponential advantage zone |
| AUDIT Window | 4 rows | Conservative estimates | Toy model only | Slow = near-classical | Medium = quadratic | Fast = exponential | Educational level | College friendly | Demonstrates scaling concepts |
Note. All classical simulations here refer to a standard Windows 11 laptop.
| Index | Desired Accuracy | Classical Trials | Simulation Interference Trials | Classical Complexity | Quantum Complexity (BQP) | Abbrev. Quantum Alg | Abbrev. Classical Alg | Quibble Notes |
|---|---|---|---|---|---|---|---|---|
| 1 | 3 decimals | ~10,000,000 | ~1,000,000 | P (feasible) | BQP (easy) | QAE / Grover | Monte Carlo | Noticeable improvement |
| 2 | 5 decimals | ~1,000,000,000 | ~100,000,000 | P (slow) | BQP (fast) | Amplitude Estimation | Monte Carlo | Strong improvement |
| 3 | 8 decimals | huge (10^16+) | large (10^14+) | EXP / superpolynomial | BQP (manageable) | QAE | Standard MC | Quantum advantage visible |
| 4 | 10+ decimals | impractical | very slow | EXP (impractical) | BQP (feasible on large QC) | Amplitude Estimation | Classical MC | Exponential advantage zone |
| AUDIT Window | 4 rows | Conservative estimates | Toy model only | Classical scaling | Quantum scaling | Educational level | College friendly | Demonstrates complexity classes |
sP = Polynomial time (feasible on classical computers) BQP = Bounded-error Quantum Polynomial time (feasible on quantum computers) EXP = Exponential time (impractical on classical computers)
Note. All classical simulations here refer to a standard Windows 11 laptop.
Note. There appears to be slow, medium or fast paths for a potential quantum algorithm solution. Maybe depends on Quantum algorithms, problem type, token economics, or "implementation = hardware" terms.
| Index | Year | Event | Note |
|---|---|---|---|
| 1 | 1994 | Shor’s algorithm | factoring + discrete log speedup |
| 2 | 1996 | Grover’s algorithm | unstructured search |
| 3 | 2005 | QAE framework | amplitude estimation, MC analogue |
| 4 | 2010s | Shor refinements | circuits, resource counts, FT needs |
| 5 | 2010s | Grover refinements | oracle cost, amplification, variants |
| 6 | 2010s | QAE variants | iterative, MLE, low-depth forms |
| 7 | 2020s | hardware era | noise, depth, overhead dominate |
| — | Ongoing | many teams | theory, compilers, demos, benchmarks |
| Index | Year | Event | Note |
|---|---|---|---|
| 1 | 1982 | Feynman sim. idea | quantum systems may need quantum machines |
| 2 | 1985 | Deutsch model | universal quantum computer idea |
| 3 | 1994 | Shor’s algorithm | factoring + discrete log speedup |
| 4 | 1996 | Grover’s algorithm | unstructured searxh |
| 5 | 2005 | QAE framework | amplitude estimation, Monte Carlo analogue |
| 6 | 2010s | fault-tolerance focus | qubits, gates, error corr. overhead |
| 7 | 2020s | resource-estimate era | cost, depth, hardware limits |
| — | Ongoing | many teams | theory, compilers, demos, FT roadmaps |
| Index | Year | Event | Note |
|---|---|---|---|
| 1 | 1995–1996 | Peter Shor introduces the first QEC code | Shor proposes the 9-qubit code that corrects arbitrary single-qubit errors |
| 2 | 1996 | Andrew Steane develops the Steane code | Steane introduces the 7-qubit CSS code with improved efficiency |
| 3 | 1996–1997 | Calderbank-Shor-Steane (CSS) framework | Robert Calderbank, Peter Shor, and Andrew Steane formalize CSS codes |
| 4 | 1998–2003 | Topological and surface codes | Alexei Kitaev introduces toric code; surface code variants emerge for scalability |
| 5 | 2000s–2010s | Stabilizer codes and theory advances | Researchers develop fault-tolerant gate sets and threshold theorems |
| 6 | 2010s | Early experimental demonstrations | Teams implement small QEC codes on nuclear magnetic resonance, trapped-ion, and superconducting platforms |
| 7 | 2020s | Logical qubit breakthroughs | Google and others demonstrate error-corrected logical qubits below break-even point using surface codes |
| 8 | 2020s–present | Scaling efforts | Multiple teams pursue larger code distances and real-time error correction on NISQ devices |
| — | Ongoing | Fault-tolerance roadmap | Research groups focus on practical thresholds, hardware-specific codes, and integration with algorithms |
Foundational algorithm, includes other related quantum algoritms.
| Index | Year | Event | Note |
|---|---|---|---|
| 1 | 1996 | Grover's algorithm foundation | Lov Grover introduces amplitude amplification as the basis for search and estimation |
| 2 | 2000–2002 | QAE framework formalized | Gilles Brassard, Peter Høyer, Michele Mosca, and Alain Tapp develop Quantum Amplitude Estimation as a Monte Carlo analogue |
| 3 | 2000s | Theoretical variants emerge | Researchers create iterative QAE, maximum likelihood estimation (MLE) versions, and amplitude amplification extensions |
| 4 | Early 2010s | Circuit optimizations | Teams reduce circuit depth and qubit requirements for near-term hardware |
| 5 | 2010s–2020s | First hardware demonstrations | Groups implement QAE on nuclear magnetic resonance, photonic, trapped-ion, and superconducting platforms |
| 6 | 2020s | Application-focused implementations | Research teams apply QAE to quantum finance (option pricing), chemistry, and machine learning |
| 7 | 2020s | Error-mitigated and hybrid QAE | Multiple groups develop noise-resilient versions, variational approaches, and classical-quantum hybrids |
| — | Ongoing | Scalable QAE research | Worldwide efforts target fault-tolerant QAE, resource estimation, and integration with other quantum algorithms |
----.
Lov Grover developed Grover's algorithm in 1996. The algorithm provides a quadratic speedup for unstructured search problems. Grover's work complements Shor's algorithm and serves as a core primitive in many quantum algorithms.
Wiki Table: Grover's Algorithm Timeline – Key Milestones
| Index | Year | Event | Note |
|---|---|---|---|
| 1 | 1996 | Lov Grover proposes the algorithm | Indian-American computer scientist at Bell Labs introduces quantum search with quadratic speedup |
| 2 | Late 1990s | Theoretical extensions | Researchers develop amplitude amplification framework and applications beyond search |
| 3 | Early 2000s | First experimental demonstrations | Teams implement small-scale versions using nuclear magnetic resonance and other platforms |
| 4 | 2000s–2010s | Photonic and ion trap implementations | Groups demonstrate Grover search on photonic qubits and trapped-ion systems |
| 5 | 2010s | Superconducting qubit experiments | Research teams run Grover's algorithm on superconducting processors with increasing qubit counts |
| 6 | 2020s | Scalable and optimized implementations | Teams focus on noisy intermediate-scale quantum devices, error mitigation, and larger search spaces |
| 7 | 2020s | Applications in state preparation and optimization | Researchers adapt Grover techniques for quantum machine learning and combinatorial problems |
| — | Ongoing | Hardware and hybrid efforts | Multiple groups pursue fault-tolerant versions, classical simulations, and integration with other quantum algorithms |
| Index | Year | Event | Note |
|---|---|---|---|
| 1 | 2010s | Early small-code experiments | Teams demonstrate basic error detection on few-qubit repetition and stabilizer codes |
| 2 | 2019–2022 | Google Quantum AI surface code scaling | Demonstrates error reduction by increasing physical qubits in surface code logical qubit |
| 3 | 2023–2024 | Beyond break-even demonstrations | Google achieves logical error rate below physical qubit rate with surface code |
| 4 | 2024 | IBM quantum low-density parity check codes | IBM demonstrates [144,12,12] bivariate bicycle code encoding multiple logical qubits |
| 5 | 2024–2025 | Neutral atom and trapped-ion advances | Companies like QuEra, Quantinuum, and Atom Computing report logical qubit experiments with competitive overhead |
| 6 | 2025–2026 | Industry benchmarking frameworks | Alice & Bob and others propose standardized five-criteria evaluation for logical qubit claims |
| 7 | 2020s | Multi-logical-qubit operations | Teams progress toward logical gates and small algorithms on encoded qubits |
| — | Ongoing | Scaling and standardization | Research focuses on distance scaling, real-time decoding, and magic state distillation benchmarks |
Peter Shor's work sparked intense interest in quantum computing as a practical technology.
| Index | Year | Event | Note |
|---|---|---|---|
| 1 | 1994 | Peter Shor proposes the algorithm | American mathematician at Bell Labs introduces polynomial-time quantum factoring and discrete logarithm solution at the Foundations of Computer Science conference |
| 2 | 1994–1995 | Initial theoretical refinements | Researchers analyze circuit complexity and error correction needs for fault-tolerant execution |
| 3 | 2001 | First experimental demonstration by IBM team | IBM Research-Almaden group factors 15 using 7-qubit liquid-state nuclear magnetic resonance quantum computer |
| 4 | Early 2010s | Photonic and solid-state implementations | Independent teams demonstrate variants; one photonic setup factors 21 |
| 5 | 2012 | Superconducting processor demonstration | Team achieves factorization of 15 on superconducting qubits |
| 6 | 2016 | Trapped-ion implementation | Researchers factor 15 with trapped-ion qubits and qubit recycling technique |
| 7 | 2019 | Larger number attempt on IBM Q System One | Team attempts to factor 35 on superconducting hardware |
| 8 | 2020s | Resource estimation and compilation focus | Multiple teams optimize circuits, reduce qubit and gate counts, and address noise limitations |
| — | Ongoing | Hardware and simulation efforts | Research groups worldwide pursue scalable versions, error-corrected demonstrations, and educational tools |
Note. These Snippets on Theoretical Physics are a set, not stand alones. Recommend read all of the set.
TCL Wiki has numerous excellent pages on Monte Carlo methods, largely from arjen .
Note. The ink is hardly dry on some of these papers. Don't know what gems are hidden, if I dig deeper.
Classical: Double the digits gives 100 times more trials Simulation Interference: Double the digits gives 10 to 30 times more trials Quantum (quadratic): Double the digits gives 10 times more trials Quantum (exponential): Double the digits gives almost no extra trials
Note. Very different notation than used before.
Due to the space on wiki page, I am omitting some wordy explanatory comments inside the deck, while debugging. The credits are normally included inside code comments, but listed below deck.
# Classical Simulation of Shor’s Algorithm V5
# in pure Tcl 8.6+ for tutorial purposes.
# Tcl 8.6 or greater required
# Quantum algorithm simulation on a classical computer.
# Classical Simulation code does not provide Quantum Speedup.
# Quantum Speedup requires actual Quantum hardware
# and Quantum Error Correction QEC.
# Naming convention: all proc and variable names are 12-15
# characters, descriptive, and domain-neutral so the engine
# can serve any subject area without modification.
#
# ----
# Compatible with Tcl/Tk (Tool Command Language / Toolkit) 8.6+
# Written for Windows 11 on ActiveState Tcl.
# Use Pure 7-bit ASCII code, no Unicode characters used anywhere.
# ----
# Using modular snippets inside modular structured programs.
# Modules should be 15 to 25 lines long without comments.
# Small length modules
# are believed to aid future code maintenance.
# In theory, module isolation should
# allow easier maintenance.
# Program deck may contain multiple estimation procs.
# Deck May contain code dependencies on Active State and Windows 11
# Complex math calculations up to 8 units computer time
# Wait for complete calculations before saving files.
# Proc names and variables names need to be very human readable
# and very explanatory.
# Avoid variables with single letter names.
# Whereas single letter names are known to lead
# to many historic errors.
# Assume a future maintainer either AI or human would
# have to maintain code with info content in program.
# This is Experimenting Draft,
# and not a replacement for TCL Core.
# This is a hacker's patch, not rigorously derived.
# appears correct solutions for autotests.
# TCL Club 8/8/2026
#
# Revision 5 change notes:
# Reorganized into ::shor_engine namespace
# Ref compatible layout in the Grover Oracle V5 file:
# number_theory - pure math primitives, no I/O
# factor_core - pure Shor period-finding logic, no I/O
# io_utils - console logging / ascii sanitizing, no math
# formatters - pure string/row building, no file handles
# reports - file-writing drivers only, no formatting logic
# No algorithm or formula changes versus V4.
# Row layouts,
# file formats, and autotest numbers are unchanged.
# In theory, module isolation should
# allow easier maintenance.
#
if {[llength [info commands console]] > 0} {
console show
}
namespace eval ::shor_engine {
# number_theory module: pure math primitives, no I/O
namespace eval number_theory {
namespace path [list ::shor_engine]
proc calc_gcd_value {num_a num_b} {
set local_a $num_a
set local_b $num_b
if {$local_a < 0} {
set local_a [expr {-1 * $local_a}]
}
if {$local_b < 0} {
set local_b [expr {-1 * $local_b}]
}
while {$local_b != 0} {
set remain_val [expr {$local_a % $local_b}]
set local_a $local_b
set local_b $remain_val
}
return $local_a
}
proc check_if_prime {test_num} {
if {$test_num < 2} {
return 0
}
if {$test_num == 2} {
return 1
}
if {[expr {$test_num % 2}] == 0} {
return 0
}
set limit_val [expr {int(sqrt($test_num)) + 1}]
for {set div_num 3} {$div_num <= $limit_val} {incr div_num 2} {
if {[expr {$test_num % $div_num}] == 0} {
return 0
}
}
return 1
}
proc is_perfect_pow {test_num} {
if {$test_num < 4} {
return 0
}
set max_exp_val [expr {int(log($test_num)/log(2)) + 1}]
for {set exp_val 2} {$exp_val <= $max_exp_val} {incr exp_val} {
set root_val [expr {pow($test_num, 1.0/$exp_val)}]
set round_root [expr {int($root_val + 0.5)}]
if {[expr {$round_root ** $exp_val}] == $test_num} {
return 1
}
}
return 0
}
proc find_perfect_root {test_num} {
if {$test_num < 4} {
return 0
}
set max_exp_val [expr {int(log($test_num)/log(2)) + 1}]
for {set exp_val 2} {$exp_val <= $max_exp_val} {incr exp_val} {
set root_val [expr {pow($test_num, 1.0/$exp_val)}]
set round_root [expr {int($root_val + 0.5)}]
if {[expr {$round_root ** $exp_val}] == $test_num} {
return $round_root
}
}
return 0
}
proc factor_down_to_primes {number_val} {
if {$number_val <= 1} {
return {}
}
set factor_list {}
set remain_val $number_val
set div_val 2
while {[expr {$div_val * $div_val}] <= $remain_val} {
while {[expr {$remain_val % $div_val}] == 0} {
lappend factor_list $div_val
set remain_val [expr {$remain_val / $div_val}]
}
incr div_val
}
if {$remain_val > 1} {
lappend factor_list $remain_val
}
return $factor_list
}
}
# factor_core module: pure Shor period-finding logic, no I/O
# calc_mod_power and find_period_num are classical simulation
# stubs / subs for the possible Quantum Routine in Shor's
# Algorithm. Placeholder for a real quantum call (Qiskit, etc.)
namespace eval factor_core {
namespace path [list ::shor_engine]
proc calc_mod_power {base_num exp_num mod_num} {
if {$mod_num == 1} {
return 0
}
set result_val 1
set base_work [expr {$base_num % $mod_num}]
set exp_work $exp_num
while {$exp_work > 0} {
if {[expr {$exp_work % 2}] == 1} {
set result_val [expr {($result_val * $base_work) % $mod_num}]
}
set exp_work [expr {$exp_work / 2}]
set base_work [expr {($base_work * $base_work) % $mod_num}]
}
return $result_val
}
proc get_coprime_val {modulus_num} {
set max_tries_num 100
for {set try_count 1} {$try_count <= $max_tries_num} {incr try_count} {
set candid_val [expr {2 + int(rand() * ($modulus_num - 2))}]
set gcd_check_val [number_theory::calc_gcd_value $candid_val $modulus_num]
if {$gcd_check_val == 1} {
return $candid_val
}
}
return 0
}
proc find_period_num {base_num mod_num max_period} {
set running_val [expr {$base_num % $mod_num}]
set period_try 1
while {$period_try <= $max_period} {
if {$running_val == 1} {
return $period_try
}
set running_val [expr {($running_val * $base_num) % $mod_num}]
incr period_try
}
return 0
}
proc try_factor_num {target_num max_period} {
if {[number_theory::check_if_prime $target_num]} {
return [list prime_num 0 0]
}
if {[expr {$target_num % 2}] == 0} {
return [list even_num 2 [expr {$target_num / 2}]]
}
if {[number_theory::is_perfect_pow $target_num]} {
set root_val [number_theory::find_perfect_root $target_num]
set other_val [expr {$target_num / $root_val}]
return [list perfect_pow $root_val $other_val]
}
set base_num [get_coprime_val $target_num]
if {$base_num == 0} {
return [list no_coprime 0 0]
}
set period_val [find_period_num $base_num $target_num $max_period]
if {$period_val == 0 || [expr {$period_val % 2}] == 1} {
return [list retry_needed 0 0]
}
set half_period [expr {$period_val / 2}]
set power_val [calc_mod_power $base_num $half_period $target_num]
set value_low [expr {($power_val - 1) % $target_num}]
set value_high [expr {($power_val + 1) % $target_num}]
set factor_low [number_theory::calc_gcd_value $value_low $target_num]
set factor_high [number_theory::calc_gcd_value $value_high $target_num]
if {$factor_low > 1 && $factor_low < $target_num} {
set other_val [expr {$target_num / $factor_low}]
return [list success $factor_low $other_val]
}
if {$factor_high > 1 && $factor_high < $target_num} {
set other_val [expr {$target_num / $factor_high}]
return [list success $factor_high $other_val]
}
return [list retry_needed 0 0]
}
proc run_shor_demo {target_num max_period} {
set attempt_limit 20
for {set attempt_num 1} {$attempt_num <= $attempt_limit} {incr attempt_num} {
set try_result [try_factor_num $target_num $max_period]
set status_word [lindex $try_result 0]
if {$status_word == "retry_needed" || $status_word == "no_coprime"} {
continue
}
set factor_a [lindex $try_result 1]
set factor_b [lindex $try_result 2]
return [list $status_word $factor_a $factor_b $attempt_num]
}
return [list failed_limit 0 0 $attempt_limit]
}
}
# io_utils module: console logging and file primitives
# (identical pattern to the Grover V5 io_utils module)
namespace eval io_utils {
namespace path [list ::shor_engine]
variable console_log_channel ""
proc sanitize_ascii_text {text_value} {
set output_text ""
set text_length [string length $text_value]
for {set char_index 0} {$char_index < $text_length} {incr char_index} {
set one_char [string index $text_value $char_index]
scan $one_char %c one_code
if {$one_code > 127} {
append output_text "?"
} else {
append output_text $one_char
}
}
return $output_text
}
proc write_ascii_line {channel_id text_value} {
puts $channel_id [sanitize_ascii_text $text_value]
}
proc build_date_stamp {} {
return [clock format [clock seconds] -format {%Y%m%d_%H%M%S}]
}
proc start_console_log {} {
variable console_log_channel
set stamp_text [build_date_stamp]
set log_file_name "shor_console_log_${stamp_text}.txt"
set console_log_channel [open $log_file_name w]
write_ascii_line $console_log_channel "Shor Simulation Console Log, Revision 5"
write_ascii_line $console_log_channel "Created: $stamp_text"
write_ascii_line $console_log_channel "Encoding: pure 7-bit ASCII, sanitized at write time"
write_ascii_line $console_log_channel "-----------------------------------"
return [list $log_file_name $stamp_text]
}
proc log_console_line {message_text} {
variable console_log_channel
set safe_text [sanitize_ascii_text $message_text]
puts $safe_text
if {$console_log_channel ne ""} {
puts $console_log_channel $safe_text
}
}
proc stop_console_log {} {
variable console_log_channel
if {$console_log_channel ne ""} {
close $console_log_channel
set console_log_channel ""
}
}
}
# formatters module: pure string/row building, no file handles,
# no puts. Everything here returns text; nothing here writes it.
namespace eval formatters {
namespace path [list ::shor_engine]
proc make_abbrev_list {factor_a_val factor_b_val} {
set combined_list {}
if {$factor_a_val > 0} {
foreach one_prime [number_theory::factor_down_to_primes $factor_a_val] {
lappend combined_list $one_prime
}
}
if {$factor_b_val > 0} {
foreach one_prime [number_theory::factor_down_to_primes $factor_b_val] {
lappend combined_list $one_prime
}
}
return [lsort -integer $combined_list]
}
proc format_abbrev_text {prime_list} {
set text_val "\["
append text_val [join $prime_list ","]
append text_val "\]"
return $text_val
}
proc make_quibble_note {status_word abbrev_list} {
if {$status_word == "prime_num"} {
return "Prime number"
}
if {$status_word == "failed_limit"} {
return "No factors found"
}
if {$status_word == "perfect_pow"} {
set list_len [llength $abbrev_list]
if {$list_len == 2} {
return "Perfect square"
}
if {$list_len == 3} {
return "Perfect cube"
}
return "Perfect power"
}
if {[llength $abbrev_list] > 2} {
return "Multiple factors"
}
return "Small composite"
}
proc count_successes {result_list} {
set ok_count 0
foreach one_result $result_list {
lassign $one_result idx_val tgt_val f1_val f2_val abbrev_val type_val note_val
if {$f1_val > 0} {
incr ok_count
}
}
return $ok_count
}
proc build_dump_lines {result_list} {
set lines {}
lappend lines "INDEX TARGET FACTOR1 FACTOR2 ABBREV_LIST RESULT_TYPE QUIBBLE_NOTES"
foreach one_result $result_list {
lassign $one_result idx_val tgt_val f1_val f2_val abbrev_val type_val note_val
lappend lines [format "%s %s %s %s %s %s %s" \
$idx_val $tgt_val $f1_val $f2_val $abbrev_val $type_val $note_val]
}
set ok_count [count_successes $result_list]
lappend lines "AUDIT total_tests=[llength $result_list] successes=$ok_count"
return $lines
}
proc build_wiki_lines {result_list} {
set lines {}
lappend lines "%| Index | Target Number | Break Factor 1 | Break Factor 2 | Abbrev Factors List | Result Type | Quibble Notes |%"
foreach one_result $result_list {
lassign $one_result idx_val tgt_val f1_val f2_val abbrev_val type_val note_val
lappend lines [format "&| %s | %s | %s | %s | %s | %s | %s |&" \
$idx_val $tgt_val $f1_val $f2_val $abbrev_val $type_val $note_val]
}
set ok_count [count_successes $result_list]
set bad_count [expr {[llength $result_list] - $ok_count}]
set word_text [expr {$bad_count == 1 ? "special case" : "special cases"}]
lappend lines [format "&| AUDIT Window | %s numbers | - | - | - | %s successes | %s %s |&" \
[llength $result_list] $ok_count $bad_count $word_text]
return $lines
}
}
# reports module: file-writing drivers only.
# Takes lines already built by formatters and writes them;
# does no row building, counting, or classification itself.
namespace eval reports {
namespace path [list ::shor_engine]
proc save_text_dump {file_name stamp_text lines_list} {
set fh [open $file_name w]
io_utils::write_ascii_line $fh "Shor Text Dump Report, Revision 5"
io_utils::write_ascii_line $fh "Created: $stamp_text"
io_utils::write_ascii_line $fh "Encoding: pure 7-bit ASCII, sanitized at write time"
io_utils::write_ascii_line $fh ""
foreach one_line $lines_list {
io_utils::write_ascii_line $fh $one_line
}
close $fh
}
proc save_wiki_table {file_name stamp_text lines_list} {
set fh [open $file_name w]
io_utils::write_ascii_line $fh "Shor Wiki Table Report, Revision 5"
io_utils::write_ascii_line $fh "Created: $stamp_text"
io_utils::write_ascii_line $fh "Encoding: pure 7-bit ASCII, sanitized at write time"
io_utils::write_ascii_line $fh ""
foreach one_line $lines_list {
io_utils::write_ascii_line $fh $one_line
}
close $fh
}
}
# main controller layer
proc run_shor_test {target_num max_period test_label} {
io_utils::log_console_line ""
io_utils::log_console_line "-- $test_label --"
io_utils::log_console_line "Target number to factor: $target_num"
set demo_result [factor_core::run_shor_demo $target_num $max_period]
lassign $demo_result status_word factor_a factor_b attempt_num
if {$status_word == "prime_num"} {
io_utils::log_console_line "Number is prime. No factors needed."
} elseif {$status_word == "perfect_pow"} {
io_utils::log_console_line "Number is a perfect power."
io_utils::log_console_line "Complete factors: $factor_a and $factor_b"
} elseif {$status_word == "failed_limit"} {
io_utils::log_console_line "Failed to find factors after retry limit."
} else {
io_utils::log_console_line "Found factor: $factor_a"
io_utils::log_console_line "Complete factors: $factor_a and $factor_b"
}
return $demo_result
}
proc run_auto_tests {} {
set test_numbers {15 21 35 33 77 91 9 49 97 100}
lassign [io_utils::start_console_log] log_file_name stamp_text
io_utils::log_console_line "Shor auto test run started."
io_utils::log_console_line "Console log file: $log_file_name"
set dump_file_name "shor_text_dump_${stamp_text}.txt"
set wiki_file_name "shor_wiki_table_${stamp_text}.txt"
set result_list {}
set index_num 1
foreach one_number $test_numbers {
set test_label "Test $index_num (target=$one_number)"
set demo_result [run_shor_test $one_number 200 $test_label]
lassign $demo_result status_word factor_a factor_b attempt_num
set abbrev_list [formatters::make_abbrev_list $factor_a $factor_b]
set abbrev_text [formatters::format_abbrev_text $abbrev_list]
set note_text [formatters::make_quibble_note $status_word $abbrev_list]
lappend result_list [list $index_num $one_number $factor_a $factor_b \
$abbrev_text $status_word $note_text]
incr index_num
}
set dump_lines [formatters::build_dump_lines $result_list]
set wiki_lines [formatters::build_wiki_lines $result_list]
reports::save_text_dump $dump_file_name $stamp_text $dump_lines
reports::save_wiki_table $wiki_file_name $stamp_text $wiki_lines
io_utils::log_console_line ""
io_utils::log_console_line "Autotests complete. Files written:"
io_utils::log_console_line " $log_file_name"
io_utils::log_console_line " $dump_file_name"
io_utils::log_console_line " $wiki_file_name"
io_utils::stop_console_log
return $result_list
}
namespace export run_auto_tests
}
::shor_engine::run_auto_tests
# End of file# References. # # Inspired by counterfactual principles discussed in Chiara Marletto's book # "The Science of Can and Can't: A Physicist's Journey Through the Land of Counterfactuals" (2021). # The dummy subroutine implements a generic simulation # for educational purposes only. # puts "Credits" # The algorithm (Shor’s) is public domain, # and mathematical knowledge since 1994. # Peter Shore, Original 1994 Conference Paper # Algorithms for Quantum Computation: Discrete Logarithms and Factoring # Peter Shore, Polynomial-Time Algorithms for Prime Factorization # and Discrete Logarithms on a Quantum Computer (1995 expanded version) puts "Reference: Maria Violaris, arXiv:2601.08102v1, January 2026" puts "Reference: https://wiki.tcl-lang.org/page/Snippets+Quantum+Many+Worlds" puts "Based on ref. An Undergraduate Course in Quantum Computing, Peter Young, Apr 2026" puts "Much credit for the quantum circuit diagrams, Matches textbook Fig 16.4 etc" puts "University of California Santa Cruz, CA, arXiv:2604.10396"
| Index | Target Number | Break Factor 1 | Break Factor 2 | Abbrev Factors List | Result Type | Quibble Notes |
|---|---|---|---|---|---|---|
| 1 | 15 | 3 | 5 | [3,5] | success | Small composite |
| 2 | 21 | 3 | 7 | [3,7] | success | Small composite |
| 3 | 35 | 7 | 5 | [5,7] | success | Small composite |
| 4 | 33 | 3 | 11 | [3,11] | success | Small composite |
| 5 | 77 | 11 | 7 | [7,11] | success | Small composite |
| 6 | 91 | 7 | 13 | [7,13] | success | Small composite |
| 7 | 9 | 3 | 3 | [3,3] | perfect_pow | Perfect square |
| 8 | 49 | 7 | 7 | [7,7] | perfect_pow | Perfect square |
| 9 | 97 | 0 | 0 | [] | prime_num | Prime number |
| 10 | 100 | 2 | 50 | [2,2,5,5] | even_num | Multiple factors |
| AUDIT Window | 10 numbers | - | - | - | 9 successes | 1 special |
Note. Prime numbers can not be factored.
Note. Random base selection can fail silently after 100 tries May need a flag here on V5.
# Inside proc run_shor_test, after stm' lassign:tcl
if {$status_word eq "failed_limit"} {
io_utils::log_console_line "*** FLAG: failed_limit on target $target_num ***"
}Note. Using Automatic Return in Tcl Procs. If the return command is not present, the procedure automatically returns the value of the last expr statement. This is standard Tcl behavior. Very convenient, but sometimes confusing or double take for visitors from other computer languages.
Note. Caution!!!! These are drafts. We have received Caution that old fashioned ASCII Diagrams may not adequately represent phase, reflections, and timing aspects of Simulations or Quantum Circuits. For example, The full Q Operator includes both the oracle reflection and the diffuser reflection. Search keywords "Algorithm Circuit Glossary" on wiki, space limits here.
.
+----------------------------------------------------------------------------------+ | SHOR SIMULATION: OVERALL PROGRAM FLOW (proc run_auto_tests) | | | | Test number list: 15 21 35 33 77 91 9 49 97 100 | | | | +-----------------------+ | | | run_auto_tests | | | +-----------+-----------+ | | | for each test number | | v | | +-----------------------+ | | | print_shor_result | prints target number to console | | +-----------+-----------+ | | | | | v | | +-----------------------+ | | | run_shor_demo | retry loop, attempt_limit = 20 | | +-----------+-----------+ | | | calls once per attempt | | v | | +-----------------------+ | | | try_factor_num | single-attempt decision logic | | +-----------+-----------+ | | | | | +------+------+ | | | | | | status = success status = retry_needed or no_coprime | | | | | | v +--> loop back to run_shor_demo, try again | | return factor pair | | | | | v | | +-----------------------+ | | | make_abbrev_list | breaks factors down to prime numbers | | | format_abbrev_text | builds bracketed text, example [3,5] | | | make_quibble_note | writes a short plain-language note | | +-----------+-----------+ | | | | | v | | +-----------------------+ | | | save_text_dump | writes shor_test_dump.txt | | | save_wiki_table | writes shor_wiki_table.txt | | +-----------------------+ | +----------------------------------------------------------------------------------+
+----------------------------------------------------------------------------------+ | TRY_FACTOR_NUM: DECISION FLOW (single attempt, one target number) | | | | +----------------------------+ | | | input: target_num | | | +--------------+-------------+ | | | | | v | | +---------------------+ | | | check_if_prime ? |----- yes ----> return "prime_num" | | +---------+-----------+ | | | no | | v | | +---------------------+ | | | target_num even ? |----- yes ----> return "even_num", factor = 2 | | +---------+-----------+ | | | no | | v | | +---------------------+ | | | is_perfect_pow ? |----- yes ----> find_perfect_root | | +---------+-----------+ return "perfect_pow" | | | no | | v | | +---------------------+ | | | get_coprime_val |----- fails --> return "no_coprime" | | +---------+-----------+ | | | base_num found | | v | | +---------------------+ | | | find_period_num |----- period = 0 or odd --> return "retry_needed" | | +---------+-----------+ | | | period found, even | | v | | +---------------------+ | | | calc_mod_power | raises base_num to half the period, mod target | | +---------+-----------+ | | | | | v | | +---------------------+ | | | calc_gcd_value | checks power_val minus 1, and power_val plus 1 | | +---------+-----------+ | | | | | +------+------+ | | factor found no usable factor | | | | | | v v | | return "success" return "retry_needed" | +----------------------------------------------------------------------------------+
+----------------------------------------------------------------------------------+ | PERIOD FINDING LOOP (find_period_num, with helper calc_mod_power) | | Classical stand-in for the quantum Fourier transform step, abbreviated QFT | | | | Inputs: base_num, mod_num, max_period | | | | +----------------------------+ | | | running_val = base_num | | | | mod mod_num | | | | period_try = 1 | | | +--------------+-------------+ | | | | | v | | +---------------------+ | | | period_try <= |----- no ----> return 0 (no period found) | | | max_period ? | | | +---------+-----------+ | | | yes | | v | | +---------------------+ | | | running_val == 1 ? |----- yes ----> return period_try | | +---------+-----------+ | | | no | | v | | +----------------------------------+ | | | running_val = (running_val | | | | times base_num) mod mod_num | | | | incr period_try | | | +--------------+---------------------+ | | | | | +----> loop back to the period_try test | | | | Note on calc_mod_power (separate helper procedure): | | Uses repeated squaring, so the exponent halves on every pass. | | This keeps modular exponentiation fast even for large exponents. | +----------------------------------------------------------------------------------+
+----------------------------------------------------------------------------------+ | PROGRAM OVERVIEW – PI ESTIMATION WITH QAE | | | | Goal: Estimate π/4 as the probability that a random (x, y) point | | lies inside the quarter circle x² + y² ≤ R². | | | | Method: Quantum Amplitude Estimation (QAE) | | 1. Build exact oracle that marks good (x, y) states | | 2. Prepare uniform superposition over all (x, y) | | 3. Use Grover operator to amplify the good states | | 4. Estimate the amplitude of the "good" subspace | | 5. Multiply by 4 to recover π estimate | | | | Practical Limit: Small n_bits (≤4) due to oracle size and qubit count. | +----------------------------------------------------------------------------------+
+----------------------------------------------------------------------------------+ | QUARTER CIRCLE ORACLE CONSTRUCTION | | | | Input: n_bits (e.g. 3 → 7 data/flag qubits) | | | | Method: Brute-force enumeration | | For every x, y in 0..2^n_bits-1: | | If x² + y² ≤ R² (R = 2^n_bits - 1): | | Apply multi-controlled-X on (x, y) to flip flag bit | | | | Result: Oracle that flags "good" states inside the quarter circle. | | Cost: Grows like 4^n_bits gates — exact but only practical for small n_bits. | +----------------------------------------------------------------------------------+
+----------------------------------------------------------------------------------+ | PI ESTIMATION CIRCUIT FLOW | | | | 1. State Preparation (A): | | Uniform superposition over (x, y) + oracle to mark good states | | | | 2. Phase Oracle: Z gate on flag qubit (marks good states with phase) | | | | 3. Grover Operator: Reflects about good subspace to amplify amplitude | | | | 4. Amplitude Estimation: Uses phase estimation to estimate the amplitude | | of the good subspace (≈ π/4) | | | | Final: pi_est = 4 * estimated_amplitude | +----------------------------------------------------------------------------------+
figure. QAE RESULT EXAMPLE (n_bits=3, precision=3)**
+----------------------------------------------------------------------------------+ | QAE RESULT EXAMPLE (n_bits=3, precision=3) | | | | Qubits: 7 data/flag + 3 evaluation = 10 total qubits | | | | Output: | | Estimated amplitude (π/4) : 0.7854 | | Estimated π : 3.1416 | | True π : 3.1416 | | Absolute Error : ~0.0000 | | | | Note: Larger n_bits improves geometric accuracy but explodes gate count. | +----------------------------------------------------------------------------------+
+----------------------------------------------------------------------------------+ | PROGRAM FLOW – MAIN STEPS | | | | 1. create_quarter_circle_oracle → exact marking oracle | | 2. create_pi_estimation_circuit → full EstimationProblem | | 3. estimate_pi_qae → runs AmplitudeEstimation | | 4. Print results (amplitude, π estimate, error) | | | | Safety Guard: Limits total qubits to avoid simulator crash. | +----------------------------------------------------------------------------------+
+----------------------------------------------------------------------------------+ | ORACLE COST VS ACCURACY TRADE-OFF | | | | Brute-force Oracle: | | Exact but exponential gate count (4^n_bits) | | | | Scalable Alternative (future): | | Use quantum adders and comparators for polynomial cost. | | | | Current Demo: Small n_bits only (practical on laptop). | | Educational Goal: Show exact quarter-circle marking for π estimation. | +----------------------------------------------------------------------------------+ ----
+----------------------------------------------------------------------------------+ | WHY THIS DEMO IS USEFUL | | | | • Demonstrates Quantum Amplitude Estimation on a geometric problem. | | • Shows how quantum computers can estimate π without classical Monte Carlo. | | • Highlights practical limits (qubit count, gate complexity). | | • Serves as teaching tool for quantum algorithms and oracles. | | | | Real-world QAE can be used for financial risk analysis, chemistry, etc. | +----------------------------------------------------------------------------------+
+----------------------------------------------------------------------------------+ | SHOR N=15 QISKIT: OVERALL PROGRAM FLOW (__main__ block) | | | | candidates_a = [7, 11, 13, 2, 4, 8] | | | | +-------------------------+ | | | for a in candidates_a | | | +------------+------------+ | | | | | v | | +-------------------------+ | | | shor_factor(N=15, a) | | | +------------+------------+ | | | | | +------+------+ | | result found result = None | | | | | | v v | | print factors print "no valid factors" | | break loop continue to next a | | | | | v (loop exhausted with no break) | | +-------------------------+ | | | print "failed after | | | | trying all bases" | | | +-------------------------+ | +----------------------------------------------------------------------------------+
+----------------------------------------------------------------------------------+ | SHOR_FACTOR: SINGLE ATTEMPT DECISION FLOW (N=15, base a) | | | | +----------------------------+ | | | input: N, a, shots, n_count| | | +--------------+-------------+ | | | | | v | | +---------------------+ | | | gcd(a, N) != 1 ? |----- yes ----> return gcd(a,N), N/gcd(a,N) | | +---------+-----------+ (lucky classical shortcut) | | | no | | v | | +---------------------+ | | | run_period_finding | builds and runs quantum circuit | | +---------+-----------+ | | | | | v | | +---------------------+ | | | periods_from_counts | continued fractions, weighted by frequency | | +---------+-----------+ | | | | | v | | +---------------------+ | | | for r in periods, | | | | most common first | | | +---------+-----------+ | | | | | +------+-------------------+ | | r == 0 or r odd r even | | | | | | v v | | skip, next r +----------------------+ | | | x = a^(r/2) mod N | | | +----------+-----------+ | | | | | +----------+-----------+ | | | x == N-1 ? |----- yes ----> skip, next r | | +----------+-----------+ | | | no | | v | | +----------------------+ | | | factor1 = gcd(x-1,N) | | | | factor2 = gcd(x+1,N) | | | +----------+-----------+ | | | | | +----------+-----------+ | | 1<factor1<N ? 1<factor2<N ? | | | yes | yes | | v v | | return factor1, return factor2, | | N/factor1 N/factor2 | | | | | (all r exhausted) | | v | | return None | +----------------------------------------------------------------------------------+
+----------------------------------------------------------------------------------+ | RUN_PERIOD_FINDING: QUANTUM CIRCUIT BUILD ORDER (4 + n_count qubits) | | | | Register layout: | | qubits 0 .. n_count-1 counting register | | qubits n_count .. n_count+3 auxiliary register (4 qubits, holds mod 15) | | classical bits 0 .. n_count-1 measurement output | | | | +----------------------------+ | | | Step 1: H gate on each | puts counting register into superposition | | | counting qubit (0..n-1) | | | +--------------+-------------+ | | v | | +----------------------------+ | | | Step 2: X gate on qubit | sets auxiliary register to state |1> | | | n_count (first aux qubit)| | | +--------------+-------------+ | | v | | +----------------------------+ | | | Step 3: for q in | controlled c_amod15(a, 2^q) | | | 0..n_count-1 | applied on aux register, | | | append controlled-U | controlled by counting qubit q | | +--------------+-------------+ | | v | | +----------------------------+ | | | Step 4: append qft_dagger | inverse QFT on counting register | | | on counting register | QFT = Quantum Fourier Transform | | +--------------+-------------+ | | v | | +----------------------------+ | | | Step 5: measure counting | writes to classical bits 0..n_count-1 | | | register | | | +--------------+-------------+ | | v | | +----------------------------+ | | | transpile + run on | backend = aer_simulator | | | aer_simulator, shots | | | +--------------+-------------+ | | v | | return counts | +----------------------------------------------------------------------------------+
+----------------------------------------------------------------------------------+ | C_AMOD15: CONTROLLED PERMUTATION GATE LOGIC (4-qubit U, then U.control(1)) | | | | Input: a (must be in [2,4,7,8,11,13]), power | | | | +----------------------------+ | | | a not in allowed list ? |----- yes ----> raise ValueError | | +--------------+-------------+ | | | no | | v | | +----------------------------+ | | | for _iteration in | repeat swap pattern 'power' times | | | range(power) | | | +--------------+-------------+ | | | | | +---------+---------+---------+---------+ | | | | | | | a in [2,13] a in [7,8] a in [4,11] | | | | | | | v v v | | swap(0,1) swap(2,3) swap(1,3) | | swap(1,2) swap(1,2) swap(0,2) | | swap(2,3) swap(0,1) | | | | +-------------------------------------+ | | | a in [7, 11, 13] | | | | X gate on all 4 qubits (q=0..3) | fix vs original broken code | | +-------------------------------------+ | | | | | v | | +----------------------------+ | | | U = U.to_gate() | name = "a^power mod 15" | | | c_U = U.control(1) | 1 extra control qubit added | | +--------------+-------------+ | | v | | return c_U | +----------------------------------------------------------------------------------+
+----------------------------------------------------------------------------------+ | PERIODS_FROM_COUNTS: CONTINUED FRACTIONS DECODE | | | | Input: counts (bitstring -> frequency), n_count, N | | | | +----------------------------+ | | | for output, freq in | | | | counts.items() | | | +--------------+-------------+ | | | | | v | | +----------------------------+ | | | decimal = int(output, 2) | binary string to integer | | +--------------+-------------+ | | v | | +----------------------------+ | | | phase = decimal / | measured phase, range 0 to 1 | | | (2 ** n_count) | | | +--------------+-------------+ | | v | | +----------------------------+ | | | frac = Fraction(phase) | Fraction limited to denominator <= N | | | .limit_denominator(N) | | | +--------------+-------------+ | | v | | +---------------------+ | | | frac.denominator |----- 0 -----> skip candidate | | | != 0 ? | | | +---------+-----------+ | | | yes | | v | | +----------------------------+ | | | append (denominator, freq) | denominator = candidate period r | | | to period_candidates | | | +--------------+-------------+ | | | (after all outputs processed) | | v | | +----------------------------+ | | | Counter: sum freq per r | weighted[r] += freq | | +--------------+-------------+ | | v | | return weighted (Counter of r -> total freq) | +----------------------------------------------------------------------------------+
gold 2/9/2026. Added categories, so can find message in Wiki.
gold 2/3/2025. Testing, encountered initial difficulty in saving work? Long code blocks with or unmatched wiki markup can sometimes confuse the Tcl Wiki formatting engine, especially if fences are not balanced or a line begins with markup it treats specially.
gold 2/14/2026. Added Automatic Dump of Examples, Using ActiveState.
gold 2/14/2026. convert to strict 7-bit ASCII for Playground V9. reporting error at bottom. program should run to completion with automatic test suite.
gold 2/14/2026.
gold 3/7/2026. convert to strict 7-bit ASCII for Playground V9. variables need to be human readable and very explanatory. avoid variables with single letter names. Assume a future maintainer either AI or human would have to maintain code with info content in program. the program is working the numbers correctly . so minimal changes.
gold 7/15/2026. Clarification for Readers: When I say “simulation” or “quantum-inspired simulation”, I mean a classical TCL program running on an ordinary Windows 11 laptop. I am not using a real quantum computer. These toy models are meant to help visualize difficult concepts.
Engineer here, an inch of real improvement on an algorithm is worth a mile of theory.
All results and simulations on this page are purely classical programs running on a standard Windows 11 laptop. No quantum computer or quantum circuit simulator is used.
gold 4/24/2026. Difficult for me to evaluate the Quantum math theories. The Python versions are posted in other venues. The TCL version is posted on wiki.
However, I suppose that the model inference programming using TcL could check the Yada-Yada theory for consistencies with other vouched quantum rules. However, code seems interesting from a hack programming viewpoint.
Essentially describing a weighted token scoring system. The same math LLMs use, just without the giant weight matrices.
evidence_tokens → score each conclusion → normalize → top-N conclusions
gold 6/26/2026. Note. Realize that this is very difficult subject without background. But human readers want a pragmatic bottom line on program results. Program output is very abstract, bare minimal like CLI.
Cutoff date of 7/22/2026.
Please place any comments here with your wiki MONIKER and date, Thanks.gold 7/18/2026
gold 7/18/2026. Disclaimer on Classical Approximations. The classical implementations and period-finding algorithms discussed here are useful for simulation, education, and comparison purposes. Classical Approximations do not provide the exponential speedup that defines the full quantum Shor’s Algorithm. Classical period-finding methods can work for small numbers but become impractical for large integers due to computational complexity. These Classical approximations help illustrate the structure of the algorithm and allow testing of supporting components in languages such as Tcl/Tk or Python. But the approximations are not substitutes for the quantum subroutine (period finding via Quantum Fourier Transform) that requires actual quantum hardware or a quantum simulator.
gold 7/18/2026. Shor’s Algorithm can be divided into classical and quantum stages. The preparatory steps (including modular exponentiation) can be implemented in classical languages such as Python with STIM or Tcl/Tk. The core quantum subroutine as period finding using the Quantum Fourier Transform does require a quantum computer and is typically written in frameworks like >>> IBM Qiskit.<<< Classical period-finding algorithms exist and are documented on the wiki for comparison.
3. Draft. Simulation Quantum Computer (Simplified Formulas)
Classical Error ≈ 1 / SQRT(N} , Where N = number of trials.
Quantum Trials = Square Root of Classical Trials
Quadratic Speedup (Grover-like) Trials needed ≈ √N_classical, SQRT(N).
Example: If classical needs 1,000,000 trials >>> Quantum needs ~1,000 trials.
Exponential Speedup (Shor-like)
Trials needed ≈ poly * (log N) (very small number compared to classical)
Classical Trials ≈ 2^N or 10^N Quantum Trials ≈ N² or N³
Simple version: Quantum Trials = (log N)²
Example: If classical needs 2¹⁰⁰⁰ trials (impossible) >>>> Quantum needs roughly 1,000,000 trials (feasible).
Classical Trials ≈ 2^N or 10^N Quantum Trials ≈ N² or N³
Simple version: Quantum Trials = (log N)²
Example:
For a 617-digit number (RSA-2048):
Classical: enormous number of trials (10^20+ years).
Quantum (Shor-like): roughly proportional to 617² ≈ 380,000 operations (very fast on a large quantum computer)
Quantum Trials ~ (log N)**2 , note. log sign is conventional, log |= ln QT ~ (log (2**1000))**2 QT ~ ( log (1E1001)) ** 2 QT ~ ( 1001 ** 2 ) ** 2 QT ~ 1E6
Quantum Phase Algorithm ~ SQRT ( N ) QPE ~ SQRT ( 1E6 ) QPE ~ 1E3
Cutoff date of 7/22/2026.
Note. Testing computer methods and computer programs, maybe wrong numbers.
| Category Numerical Analysis | Category Toys | Category Calculator | Category Mathematics | Category Example | Toys and Games | Category Games | Category Application | Category GUI |