Keep
total in the callee-saved register r4, and the first returned sum in the callee-saved register r5. Suppose the surrounding function has made an aligned stack frame with the local seven-halfword array at the current sp, occupying fourteen bytes in a sixteen-byte slot. One possible frame setup is push {r4,r5,r6,lr} followed by sub sp,sp,#16; the earlier code initializes total, regular, and special before this fragment. ldr r0, =regular @ assembler literal load of the global array address
movs r1, #7
bl sum16
movs r5, r0 @ first sum must survive the next call
add r0, sp, #0 @ current frame's local special array
movs r1, #7
bl sum16
muls r0, r5, r0 @ second sum times first sum
adds r4, r4, r0 @ update totalThe AAPCS32 permits each call to overwrite
r0–r3, r12, and condition flags, but requires preservation of r4–r8, r10, r11, and sp. Thus both r4 and r5 remain valid even if sum16 is replaced by another conforming implementation. bl changes the link processor register lr, so the enclosing function saves its own return address in its prologue. Its epilogue can use add sp,sp,#16 and pop {r4,r5,r6,pc}. The frame uses thirty-two bytes in total, preserving the required eight-byte stack pointer alignment at both calls.[ref]The two calls may be evaluated in this order. Assume the product and final addition fit the signed 32-bit result expected by the source program; unlike each individual seven-element sum, their product need not fit. The assembly language operations retain their low 32 bits if this assumption fails, whereas signed integer overflow in the C programming language has different semantics.
def eaFast(n: Int): Double = {
require(n > 0)
var remaining = n
var base = 1.0 + 1.0 / n.toDouble
var result = 1.0
while (remaining > 0) {
if (remaining % 2 == 1) result *= base
base *= base
remaining /= 2
}
result
}Writing , the exact-arithmetic loop invariant is and . For an even integer exponent , replace the base by its square and the exponent by . For an odd integer exponent , first multiply the accumulator by the base and then make the same replacement. Both preserve the product. The loop variant is
remaining, which strictly decreases while positive. At exit the remaining exponent is zero, so the returned value approximates .There are iterations, squarings and one accumulator multiplication for each set bit of : between and multiplications. Thus the bound is as , or including the small case . All power variables are
Double; no unintended Int squaring occurs.Write an -bit binary string as , where each and is most significant. Its unsigned interpretation and two's complement interpretation areEquivalently, . The ranges are through and through , respectively. The same stored bits can therefore denote different integers depending on the chosen interpretation.
A logical right shift by moves into position and fills the high positions with zero. Its unsigned interpretation isMeanwhile the original unsigned interpretation decomposes asBy integer division, , exactly the unsigned quotient. Thus the source instruction puts the required quotient into
r1. This is a proof from binary representation, rather than an assumption that every kind of right shift implements every kind of division. The displayed bit argument applies to , with endpoint operations implemented as a copy or zero where appropriate.For a 32-bit machine word and , use a left bit shift followed by a logical right shift:The left shift discards all but the lowest bits and moves those retained bits to the top. The logical right shift returns them to their original positions and fills the rest with zero. Hence
lsls r1, r0, #(32-k)
lsrs r1, r1, #(32-k)r1 contains , the remainder identified in (b). For the remainder is zero; for it is , so these endpoints can be handled directly.On a reduced instruction set computer, a bit mask such as may not fit an instruction's immediate field. Masking may therefore require materializing the constant in another processor register, possibly using several instructions or a memory load. Small shift counts are directly encodable, so the two shifts can save code space, a temporary processor register, or a load. This is an architecture-dependent advantage, rather than a universal speed claim. The source's compact instruction forms support these immediate shifts, while their bitwise AND form takes its other operand from a processor register.[ref]
Thumb 16-bit instruction set quick reference by Arm. page 1, Logical and Shift/rotate tables
Let , let , and let denote the least nonnegative residue. Here is a signed 32-bit two's complement value. The source instructions, annotated with their derived values, are:The first instruction is an arithmetic right shift, so it replicates the sign bit. The second is a logical right shift, turning the all-one word into . The paired shifts then extract the low ten bits, as in (c). Their effect is the residue of even if its two's complement interpretation is negative, because divides the word modulus . The adjusted value is representable for every input: positive inputs are unchanged, and negative inputs gain only .
rem1024:
asrs r3, r0, #31 // r3 = -s: all zero bits or all one bits
lsrs r3, r3, #22 // r3 = b = 1023*s
adds r0, r0, r3 // r0 = a+b
lsls r0, r0, #22 // r0 has word value (a+b)*2^22 modulo 2^32
lsrs r0, r0, #22 // r0 = u = (a+b) modulo 1024, in 0,...,1023
subs r0, r0, r3 // r0 = u-b
bx lr // return u-bFor , , so the return value is the usual nonnegative remainder . For , put as a mathematical integer, and write with . If , then and the return value is zero. If , thenThese are precisely the remainders for C integer division, whose quotient truncates towards zero. In every case the result has the dividend's sign or is zero, has magnitude below , and satisfies . The proof includes the smallest representable input: was used only in mathematical reasoning, not as an overflowing machine operation.[ref]
C11 committee draft N1570. section 6.5.5 paragraph 6, quotient truncation and the quotient–remainder identity
Use a three-sample run detector. Just before clock edge , let two stored bits and hold the input values at edges and . Initialise both to zero. With input , definePrimes denote the next stored state, with all assignments simultaneous at the clock edge. The output is the logical conjunction of the present input and its two preceding samples. By induction on clock edges, the stated interpretation of is maintained, proving the required behaviour. Two bits of state suffice.
Store two bits: the output , initially zero, and an
armed bit , initially one. Define the synchronous sequential circuit byHere is exclusive or, and the input restriction excludes conflicting commands. The output is the current stored .When armed, a sampled toggles and clears . Further samples leave the output unchanged. A sampled sets without changing , allowing a later to toggle it again. The same clock edge cannot both rearm and trigger because are never simultaneously high. Thus the first toggles from zero to one, and subsequent toggles each require a new followed by a later .
Share the input-history bits of (a) between a high-run detector and a low-run detector. With the two preceding input samples, putThese detector outputs are mutually exclusive. Feed them into (b). An explicit four-bit synchronous sequential circuit, with initial state , isEvery right-hand side uses the old state and the current input. In particular, the run detectors' combinational outputs are sampled by the toggle module at that same edge; there is no extra pipeline stage.
The first three consecutive high samples make at the third edge, toggling and clearing . Continuing high input cannot toggle it again. Only three consecutive low samples can make and rearm it; interrupted low runs do not suffice. After rearming, a new three-sample high run produces the next toggle. This proves the debounced toggle switch behaviour, including rejection of short high and low disturbances.
The debounced toggle switch rejects interrupted runs, toggles on the third consecutive high sample, and rearms only on the third consecutive low sample; stored outputs are shown just after each clock edge
. Details. Four state bits are necessary and sufficient. For each output value, distinguish three armed situations, remembering a trailing high run of length , and three disarmed situations, remembering a trailing low run of length . Thus a direct minimal behavioural description hasAll twelve situations are reachable. Different output values are immediately distinguishable. Within an armed group, a suitable number of high samples distinguishes the three run lengths by when the next toggle occurs. Within a disarmed group, a suitable number of low samples followed by three highs distinguishes the three rearming distances. An armed situation and a disarmed situation of the same output value are distinguished by an all-high continuation: the armed one eventually toggles and the disarmed one does not. Hence these twelve situations cannot be merged in a finite-state machine implementing the specification.
The shared-history design in (c) uses four bits, meeting this lower bound. Its sixteen encoded states have some behaviourally equivalent histories, so its encoding need not use only twelve combinations. Building two separate copies of (a) plus the two-bit module (b) would use six state-bearing elements; sharing the input history saves two.
Interpret as the bits of a binary number, with most significant. Construct a propositional formula saying that this number is strictly less than . This gives a quadratic-size formula with prescribed model count.
For , write . For each with , define the conjunctionThe empty prefix for is omitted. Let . A Boolean valuation satisfies exactly when its first difference from the binary representation of is at position , changing a one of to a zero. All later bits are unrestricted. Hence these cases are disjoint and cover exactly the numbers .
Alternatively, counting the disjoint cases directly givesEach has length , including its logical connectives and parentheses; the total length is at most a constant multiple of . The endpoints are and . If constants are unavailable and , use and instead. Assignments are counted over all specified variables, including any absent from the formula. For , the constants describe the two possible counts, zero and one. Thus the construction covers , including the endpoint zero despite the source's word “positive”.
A quadratic-size formula with prescribed model count accepts the eleven four-bit numbers below : three disjoint prefix cases contribute , and satisfying assignments
. Details. The algorithmic intention is exponentiation by squaring to compute for . With exact arithmetic, its loop invariant isInitially
result = 1, y = x, and i = n. For an even integer , squaring y and replacing i by preserves the product. For an odd integer , first multiply result by y; then . The nonnegative loop variant i decreases by halving whenever positive. At exit , so the loop invariant yields result = x^n. There are multiplication steps.Two qualifications are essential for the actual source. There is no requirement that
n be nonnegative: for every n <= 0 the printed function simply returns 1.0. Also, var y = x infers Int, so y *= y uses wrapping integer arithmetic, while the accumulator uses floating-point arithmetic. For example, anotherfunc(50000, 2L) returns -1794967296.0, rather than 2500000000.0. An exact-power loop invariant cannot prove a false claim about that execution.More precisely, for positive
n, after iterations the remaining exponent is , and the Int base is the signed 32-bit representative of modulo . The accumulator multiplies those signed representatives for the set bits of n, in increasing bit order, with a floating-point rounding after each multiplication. This describes the actual code even when the intended power law fails. In an exact implementation, use a nonnegative-exponent precondition and arbitrary-precision integers, for example:def powerExact(x: Int, n: Long): BigInt = {
require(x > 0 && n >= 0)
var result = BigInt(1)
var y = BigInt(x)
var i = n
while (i > 0) {
if (i % 2 == 1) result *= y
y *= y
i /= 2
}
result
}The displayed loop invariant applies exactly to this version. It performs logarithmically many arbitrary-precision multiplications; their bit cost grows with operand size, so that statement is not an bit-complexity bound. Merely making the accumulator a
Double does not widen the separate Int base variable. Pixel Created 2026-10-13 Updated 2026-10-31
A pixel is one picture element at an indexed position in a raster image. It can contain a single grayscale value or several colour components. The word can also refer to a physical display element; the indexed element of the stored image is the meaning used here. One stored pixel need not occupy exactly one physical display element when the image is resized. Microsoft's bitmap documentation likewise distinguishes an image's grid and its numerical colour representation.[ref]
https://learn.microsoft.com/en-us/windows/win32/gdi/about-bitmaps. Microsoft Learn, About Bitmaps: pixel grids and bitmap representations
Separate position from value: raster sampling and reconstruction concerns the spatial grid, while sample depth concerns how many bits encode each component. Four times as many pixels can describe a finer grid without improving the quantization of any value. Conversely, more bits per sample can distinguish more shades without locating an edge more precisely.
Prefix code for a rare geometric success Created 2026-10-14 Updated 2026-10-25
For a success index with geometric distribution of parameter , write , . Encode by ones followed by zero, then encode in exactly bits. This prefix code has length . Since , its expected length is the displayed expression, at most . Thus a very rare success can be communicated in approximately the logarithm of its inverse probability, rather than one bit per trial.
// Target: quantum-theory.bigb
Pseudo-polynomial time Created 2026-10-14 Updated 2026-10-20
An algorithm has pseudo-polynomial time when its running time is bounded by a polynomial in the numerical magnitudes of input quantities, rather than necessarily in their encoded length. The dynamic programming table for the 0-1 knapsack problem uses arithmetic operations for items and capacity . A binary numeral system encoding needs only bits for that capacity, so the table bound can be exponential in the number of capacity bits. This distinction does not claim that every input requires exponential work.
For each , a propositional formula over specified variables can have exactly satisfying assignments and length . For , interpret a Boolean valuation as the binary number and test whether it is less than .
For every position with , use a conjunction asserting that all earlier bits equal and , leaving later bits unrestricted. Take the disjunction of these terms. Each satisfying assignment has a unique first differing position, so the terms are disjoint, and their counts sum to . Their combined length is . Use logical falsity and logical truth at the two endpoints. The count is over all variables, including those absent from an individual term or from the whole formula.
Quantization (signal processing) 2026-10-13
Quantization maps numerical values to a specified discrete collection of representable values. In lossy block averaging, maps block arithmetic means in to eight-bit integers. Thus and . Different means can share a stored value, making this step irreversible.
Quantum algorithm Created 2026-10-20 Updated 2026-10-24
A computational procedure using quantum state preparation, controlled operations and measurement, together with any required classical processing. Complexity counts the relevant operations and repetitions; a large superposition is not itself a guarantee of a useful speedup.
Quantum information Created 2026-10-14 Updated 2026-10-18
Quantum information is information encoded in quantum states and processed through quantum channels or measurement in quantum measurements. A qubit supplies a two-dimensional state space; quantum phase and entanglement affect which operations and outcome statistics are possible. The Born rule connects the state description with the probabilities of classical measurement records.
The continuously varying probability amplitudes of a qubit do not supply a readable list of arbitrarily many classical bits. A measurement produces a classical record with state-dependent probabilities. Quantum state tomography estimates the state from many identically prepared systems. For a classical label encoded into one transmitted qubit, with no additional shared resource, Holevo's theorem bounds the mutual information available from a measurement by one bit. This bound concerns information about the label, rather than the number of possible outcome labels a measuring device can print. [ref]
https://jhwatrous.github.io/TQI-notes.pdf#page=116. Watrous's lecture notes, Lecture 12, on accessible information and the Holevo bound
Quantum information theory Created 2026-09-24 Updated 2026-10-13
Quantum information theory asks what can be stored, learned, transmitted, and protected when information is carried by quantum states. Its basic objects are density operators, measurement in quantum measurements, and quantum channels; its resources include qubits, entanglement, and classical communication. Specifying the task matters: preserving an unknown quantum state, recovering a classical bit, and estimating a probability amplitude are different demands on the same physical system.
A particularly beautiful feature is that knowing the whole need not mean knowing its parts. A Bell state is a completely specified pure state, yet either qubit alone has a maximally uncertain reduced density matrix. Conversely, two systems can share perfectly matching measurement records without entanglement. The worked Bell correlations versus a classical mixture comparison separates these possibilities using only two choices of Pauli measurement.
This viewpoint makes limitations useful design rules. Schumacher compression asks how much quantum memory a source needs; Holevo's theorem limits the classical information extractable from an encoding; quantum error correction protects states against noise. Quantum teleportation uses shared entanglement and classical communication to transfer an unknown state. Its resource accounting respects both quantum no-signalling and the no-cloning theorem.

