Let be the number of leaves; the total number of nodes is . List concatenation copies its left operand. For a tree whose left subtree contains leaves at each successive internal node, these copied lengths are . Their sum is , so the worst-case running time is .
A difference list representation avoids copying prefixes:
flattenFast :: Tree a -> [a]
flattenFast t = go t []
where
go (One x) acc = x:acc
go (Two l r) acc = go l (go r acc)The recursion invariant is
go t acc = flatten t ++ acc. The leaf case is immediate; the internal-node case uses associativity of list concatenation. Each node is visited once and each leaf contributes one output constructor, giving running time when the result is fully consumed. This is linear flattening of a binary tree and does not assume balance.Use the AAPCS32 convention:
r0 holds the input address, r1 the length, and r0 receives the result. The following Thumb instruction set assembly language uses only scratch processor registers, so no callee-saved registers need saving. Assume the array is valid, halfword-aligned, and has nonnegative length; for the mathematical sum assume it fits a signed 32-bit two's complement integer..syntax unified
.thumb
.thumb_func
sum16:
movs r2, #0 @ accumulated sum
cmp r1, #0
ble .Ldone @ empty array; also returns 0 if n < 0
.Lloop:
movs r3, #0 @ Thumb signed load needs a register offset
ldrsh r3, [r0, r3] @ signed halfword at a; offset read before r3 changes
adds r2, r2, r3 @ include this signed value
adds r0, r0, #2 @ advance by one short, not one byte
subs r1, r1, #1 @ one fewer element remains
bne .Lloop
.Ldone:
movs r0, r2 @ result register
bx lr @ leaf routine: lr was not overwrittenAfter iterations, the loop invariant is that
r2 contains the first elements' sum, r0 points to element , and r1 is . The sign extension in ldrsh supplies the correct signed addend. One iteration preserves this loop invariant, and the decreasing remaining length proves algorithm termination. For the seven-element calls, the sum lies between and , so it fits. For longer arrays that overflow, these instructions compute the sum modulo ; that is not a claim about defined signed C programming language overflow behavior. The operand forms are those of the paper's reference sheet.[ref]Thumb 16-bit instruction set quick reference by Arm. Load: signed halfword; Add/Subtract; Branch
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.
Maintain the latest five temperature readings in a circular buffer, together with their running sum. The following C programming language code spells out the message passing interface rather than assuming a particular library:
send(dst,&m) is a blocking synchronous message passing send; receive(src,&m) receives from the specified sender or ANY and returns the sender's identity; sendrec(dst,&m) atomically sends the request and waits for that sender's reply in the same message object. Successful, reliable operations are assumed. Message contents are copied by the interface.enum { ANY = -1, TIMER = 1, TEMP = 2 };
enum { PULSE, PING, REQUEST, REPLY };
typedef struct {
int type;
int period_ms;
double value;
} Message;
extern void send(int dst, const Message *m);
extern int receive(int src, Message *m);
extern void sendrec(int dst, Message *m);
void smooth(void) {
double history[5] = {0};
double sum = 0;
int count = 0, next = 0;
Message m = { .type = PULSE, .period_ms = 1000 };
send(TIMER, &m); /* subscribe once */
for (;;) {
int sender = receive(count < 5 ? TIMER : ANY, &m);
if (sender == TIMER && m.type == PING) {
Message t = { .type = REQUEST };
sendrec(TEMP, &t); /* matching REPLY contains t.value */
if (count == 5)
sum -= history[next];
else
++count;
history[next] = t.value;
sum += t.value;
next = (next + 1) % 5;
} else if (count == 5 && m.type == REQUEST) {
Message answer = { .type = REPLY, .value = sum / 5.0 };
send(sender, &answer);
}
}
}Before the fifth reading, selective reception from
TIMER prevents premature client requests from being accepted. Such clients wait at their synchronous sends; they are not given a partial arithmetic mean. Thereafter the operating-system process receives both timer messages and client requests. Each accepted PING initiates one measurement; each accepted client request returns the arithmetic mean of the five most recently completed measurements, without initiating another measurement or changing the circular buffer.The loop invariant is that
count is the number of valid readings, capped at five, sum is their sum, and next is the next unused slot during startup or the oldest slot afterwards. Removing the overwritten reading and adding the new one preserves this loop invariant. Each update and reply uses time complexity and storage, since the window length is fixed. Under timely sensor replies, timer delivery and process scheduling, measurements are initiated once per second. The next parts explain failures of these timing assumptions; the code does not promise one-second sampling when the sensor itself cannot sustain it.The kernel of a linear map is precisely , sincePart (c) gives . Apply the rank-nullity theorem to the finite-dimensional vector space , and then parts (a) and (b):This proves the dimension formula for a sum of subspaces. The kernel of a linear map records exactly the freedom to transfer a shared vector from one summand to the other without changing their sum.
For , the conditional probability mass function isThe positive denominator makes the expression well-defined, and its sum over is one.
The joint probability mass function is for . It is nonnegative and its sum over equals one. Summing over one coordinate gives the other variable's marginal distribution.
Perfect number Created 2026-10-14 Updated 2026-10-14
A perfect number is a positive integer equal to the sum of all its positive proper divisors. The divisor itself is excluded: including it gives the equivalent condition for the sum-of-divisors function. The smallest examples are and .
For comparison, has proper divisors , whose sum is : it is a deficient number. The proper divisors of are , whose sum is : it is an abundant number. The proper-divisor sum classifies these examples with the same rule, and gives , so one is not a perfect number.
Proper divisors balance a perfect number, fall short of a deficient number, or exceed an abundant number
. Original exact proper-divisor sums for . Each bar is normalized by its candidate number, and its segments are labelled with the actual proper divisors. The dashed line at one marks equality with the candidate. These are finite arithmetic calculations, not empirical data. Details.The interesting question is how such balances can be constructed without testing every smaller integer as a possible divisor. The Euclid-Euler theorem answers it for even integers: a Mersenne prime gives , and every even perfect number arises this way. For , this produces . The connection links divisor sums to primality testing for a particular family, while keeping the necessary hypotheses visible.[ref]
Euclid's Elements already gives the construction in Book IX, Proposition 36: add a succession of powers of two, and if their sum is prime, multiply by the final power of two. The modern finite geometric series makes the same pattern transparent. This original statement supplies the forward construction, rather than the converse classification of all even perfect numbers.[ref]
Perimeter of a polygon 2026-10-20
The sum of the lengths of its sides of a polygon. For a triangle with side lengths , the perimeter of a polygon is .
Polynomial Created 2026-09-24 Updated 2026-10-18
A polynomial is a finite sum of monomials with coefficients in a ring. In one variable over a commutative ring , writeThe symbol is an indeterminate: it records powers formally before we choose an input value. Finite expressions are easy to add, multiply, evaluate, and differentiate, making polynomials a common language for exact algebra and approximate numerical analysis.
Consider the real polynomialThe expanded form displays the coefficients and the degree of a polynomial; the factored form displays its roots of a polynomial. At , either description gives . At and , the factored form makes the zero values immediate. Keeping several descriptions of one object is useful because each makes a different question easy.
A simple polynomial root crosses the axis, while a double root touches it; perturbing the double factor can produce real or complex roots
. Details. The graph shows another connection. The factor changes sign across , while stays nonnegative across . Thus the graph crosses the axis at the simple root of a polynomial and touches it at the double root. Multiplicity of a root turns an algebraic repetition into visible local behavior.
For calculations, Horner's method evaluates a polynomial through nested multiplication. For modeling, a Taylor polynomial describes local behavior near a point, while polynomial interpolation constructs a polynomial matching prescribed data. Their usefulness comes with assumptions: a local approximation and an exact identity are different claims, and changing the coefficient ring can change which polynomial roots exist.
Power-law distribution 2026-10-14
A power-law distribution uses a power law for a probability mass function or a probability density on a specified range. For a continuous model with on and zero below it, the total integral is finite exactly when . Normalization then requires , giving a Pareto distribution with shape parameter . Discrete models instead normalize a sum. The support and normalizing coefficient are part of the model, and a power law for its tail probability uses a different exponent from its probability density.
Prefix sum Created 2026-09-24 Updated 2026-10-14
A prefix sum stores the accumulated sum through a specified position in a finite sequence or array. For inputs , include the empty sum and setFor the original input , the prefix array including is . A negative entry makes the accumulated sum decrease; a prefix sum does not have to be monotone. Conversely, the original entry is recovered by subtraction: .
The useful cancellation is that any contiguous block has sumBoth prefixes include the entries before ; subtracting cancels those entries. In the example, the sum from positions two through four is , recovered as . The arithmetic mean of that block is , obtained by dividing its sum by its length. Prefix sums therefore make many repeated questions about an unchanged array cheap: reuse accumulated totals instead of resumming every block.
The sequential recurrence builds all prefixes in time complexity and storage; each block query needs two reads and one subtraction, hence time complexity. These counts assume constant-cost arithmetic and access to array entries. If one input changes, all later stored prefixes change, so this simple representation is most useful when queries outnumber updates. For integer inputs, sufficient numeric capacity must be retained; with floating-point arithmetic, subtracting large nearby prefixes can lose relative accuracy for a small block total. The exact mathematical identity does not eliminate representation error.
The apparently sequential recurrence also motivates a prefix scan: associativity permits a tree of partial calculations that yields all accumulated results in parallel. Guy E. Blelloch's 1990 technical report systematically develops this operation and its applications; its authored chapter version explains the two tree sweeps used to obtain all prefixes. [ref]
https://www.cs.cmu.edu/afs/cs.cmu.edu/project/scandal/public/papers/CMU-CS-90-190.html. Blelloch, Prefix Sums and Their Applications, CMU-CS-90-190, November 1990
. [ref]https://www.cs.cmu.edu/~guyb/papers/Ble93.pdf. Blelloch, authored chapter version, §§1.1–1.2: sequential scans and parallel tree sweeps
. Probabilistic Banzhaf index 2026-10-25
The probabilistic Banzhaf index averages a player's marginal contribution over all coalitions not containing that player, each given equal weight. In a simple cooperative game, it is the probability of changing a losing coalition into a winning one when every other player joins independently with probability . Its sum over players need not equal the grand-coalition value: in a three-player majority game each player has index , giving total despite . This convention differs from both the raw count of pivotal coalitions and the normalized Banzhaf index.
The name refers to John Banzhaf, whose 1965 paper addresses the mathematical analysis of weighted voting.[ref]
Product-sum number 2026-10-20
A positive integer that is both the sum and the product of one multiset of positive integers. For factors at least with product , sum , and count , appending ones gives without changing the product. For , the example with ones proves that the smallest product-sum value is at most .
Root limit of a finite sum of powers Created 2026-10-18 Updated 2026-10-20
For finitely many fixed nonnegative real numbers , with ,Let be that maximum. If , every term is zero. Otherwise for . Taking roots gives , and . The squeeze theorem proves the result, including ties between the largest bases. For example, tends to for . The finiteness and fixed number of terms supply the upper factor ; an infinite sum needs further hypotheses.
Sample mean of iid Bernoulli variables 2026-10-14
For independent and identically distributed Bernoulli random variables with success probability , the sum has a binomial distribution. Every length- pattern with successes has probability , and the binomial coefficient counts its possible success positions. ThereforeThe usual endpoint convention includes and as deterministic cases. For and , the five probability masses are divided by . The sample mean takes values , with variance and standard deviation . At , its variance is and its standard deviation is .
Exact sample-mean distributions distinguish fresh IID draws from a copied common coin
. Original exact binomial distribution probabilities for sample sizes . Blue marks give the mass at each possible mean under independent fair draws. Orange marks give the masses for the same fair draw copied times: at zero and at one for every . These are discrete probability masses, not density values or measured histograms. Details. Second moment method Created 2026-09-24 Updated 2026-10-14
The second moment method uses a random variable's expected value and second moment to establish that a counted or measured quantity is positive with substantial probability. It is useful when a positive average alone could be caused by extremely large values on very rare outcomes. Controlling the variance rules out too much of that concentration in rare outcomes.
For a nonnegative random variable with and finite second moment, the second-moment bound for positivity givesEquivalently, . The method also includes the simpler Chebyshev's inequality bound . Thus a sequence of such random variables with has with probability tending to one. These statements require no independence assumption. The variance argument and its use for random counts are developed in Zhao's lecture notes. [ref].
For an original toy count, let count successes in ten independent Bernoulli trials with success probability . The binomial distribution givesConsequently . The exact probability is . The first moment method and union bound only give the upper bound here. First and second moments therefore answer complementary existence questions.
The second moment method certifies a positive count, while statistical dependence can change the conclusion despite an unchanged mean
. Left: exact binomial distribution probabilities of at least one success and second-moment lower bounds for ten independent trials as the success probability varies. Right: the same ten trials with either occur independently or share one common Bernoulli outcome. Both counts have mean one, but the perfectly linked count has much larger variance and only probability of being positive. All data are original specified probability models. Details.For a sum of indicator random variables, the variance of a sum isIndependence makes the covariances vanish, but the formula itself also covers dependent counts. For the same ten success probabilities, let every trial share a single Bernoulli random variable : then , with mean one, variance nine, and . The second-moment lower bound is exactly . Ignoring the positive covariances would produce the false independent-count conclusion. Zhao's discussion of sums of indicators explains why overlapping counted structures require these pairwise terms. [ref]
https://ocw.mit.edu/courses/18-226-probabilistic-methods-in-combinatorics-fall-2022/mit18_226_f22_lec06-07.pdf. Zhao, MIT 18.226, §4.1: indicator covariances and Bernoulli counts
. Series remainder 2026-10-18
For a convergent series with sum and -th partial sum , its series remainder is . It equals the sum of the terms after position . Its absolute value measures the error of replacing by ; it need not be positive when the series has signed sequence terms.




