Avoid forming the enormous powers in the original ratios. Put , and ; algebra gives
Use simultaneous exponentiation by squaring to compute the two powers with one loop and a shared remaining exponent:
def ec(n: Int): Double = {
  require(n > 1)
  val dn = n.toDouble
  val a = 1.0 + 1.0 / dn
  val b = 1.0 + 1.0 / (dn - 1.0)
  var remaining = n - 1
  var u = a
  var v = b
  var pa = 1.0
  var pb = 1.0
  while (remaining > 0) {
    if (remaining % 2 == 1) {
      pa *= u
      pb *= v
    }
    u *= u
    v *= v
    remaining /= 2
  }
  ((dn + 1.0) * a) * pa - dn * pb
}
The exact-arithmetic loop invariant is , and . The even integer and odd integer cases preserve both equalities in parallel. The loop variant is remaining. On termination, the displayed expression is exactly the desired approximation in the ideal arithmetic model. For , the loop uses at most multiplications, followed by three more: multiplications and one loop.
Converting n to Double before adding one also avoids overflowing n + 1 at Int.MaxValue. The algebra avoids power overflow but does not remove catastrophic cancellation: the final subtraction combines quantities of order to obtain a result of order . For sufficiently large , floating-point rounding can outweigh the mathematical truncation error. For example, at n == 1000000 this Double computation returns approximately 2.7180521293, although the exact formula is approximately 2.71828182845916. Arbitrarily many requested decimal digits require increased arithmetic precision, not simply a larger Int argument.
The algorithmic intention is exponentiation by squaring to compute for . With exact arithmetic, its loop invariant is
Initially 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.
The reference to part “(c)(i)” in the source is circular; the relevant modes are those verified in part (b)(i). Linearity of the heat equation and its homogeneous Dirichlet boundary conditions allows superposition of those modes:
Match the initial uniform interior temperature using the orthogonality of the Fourier sine series:
Thus for even integers and for odd integers , giving
For every , the exponential factor makes the series and the derivatives needed in the heat equation converge uniformly on later time intervals. At , the Fourier sine series equals at interior points but zero at the endpoints: the instantaneous cooling boundary condition is incompatible with the pre-immersion endpoint values. This corner mismatch is physically the idealization of an instantaneous bath contact and does not invalidate the solution for .
Figure 1.
Cooling profiles in a zero-temperature bath and the mean temperature retained after insulation
. Details.
After bath cooling followed by insulated equilibration, the remaining mean temperature is conserved: integrating the insulated heat equation gives
For constant density, specific heat capacity and cross-section, this is conservation of energy. Its Fourier cosine series has a constant mode equal to the initial integral average; every nonconstant mode decays. Therefore the eventual uniform temperature is
For each mode with an odd integer index in part (c), . Integrating the bath-cooled series yields
For , uniform convergence justifies termwise integration; the result also follows by dominated convergence of the summable positive coefficients. As a check, gives for zero bath time, and as . More bath time strictly lowers the retained average temperature when and .
Perfect matching Created 2026-09-24 Updated 2026-10-14
A perfect matching is a matching in a graph that covers every vertex exactly once. Its edges have no shared endpoints, and every vertex is an endpoint of one selected edge. It is useful when a collection must be divided into disjoint pairs with no element left over.
In a bipartite graph with equally many vertices on its two sides, a perfect matching can assign every person one allowed job and every job one person. The example under permanent of a matrix has three people and three jobs, with exactly three valid assignments. The blue edges below show those three perfect matchings; a crossing in the drawing is not an extra vertex.
Figure 1.
Three perfect matchings pair every person vertex with one job vertex along allowed edges
. Details.
Every selected edge covers two vertices, so a graph with an odd integer number of vertices has no perfect matching. An even integer number is necessary but does not guarantee existence: an isolated vertex cannot be covered. A perfect matching also need not be unique. For example, the complete bipartite graph has two perfect matchings, corresponding to the two ways of assigning two people to two jobs.
Counting all perfect matchings is a different question from finding one. For a zero-one biadjacency matrix of a balanced bipartite graph, the count is its permanent of a matrix. The nonzero determinant criterion for a perfect matching supplies an existence test, but cancellation means that a zero determinant does not rule one out.
Every finite connected cubic graph with at most two bridges has a perfect matching.
Proof. The handshaking lemma implies that the number of vertices is an even integer. Fix a nonempty subset of the vertex set, and let count the components of of odd integer order. For such a component , counting vertex degrees gives , where counts its edges to . Thus is a positive odd integer. If it is one, the unique outgoing edge is a bridge; this happens for at most two components. For all others . Therefore . Meanwhile . If , the same parity would force , contradicting the preceding bound. For there is one component of even integer order and hence . Apply Tutte's theorem on perfect matchings.
A nonnegative integer is a triangular number exactly when is a perfect square. Its square root is then an odd integer, and the row index is
Completing the square in proves necessity; reversing the calculation proves sufficiency. For example, , giving . In contrast, lies strictly between and , so twenty is not a triangular number. The criterion turns an apparently open-ended search through a sequence into one exact perfect square check.
The odd integers form an abelian group under the displayed operation. The identity element is and the inverse element of is . The bijection is a group isomorphism to , since it converts the shifted operation into addition. This illustrates how an unfamiliar identity and inverse can arise from ordinary addition by a change of coordinates.
Sieve of Eratosthenes 2026-10-14
The sieve of Eratosthenes finds all prime numbers at most an integer . Start with the integers marked as candidates. For each surviving candidate in increasing order, mark the multiples up to as composite numbers. Stop processing candidates once : the surviving candidates are exactly the prime numbers. Starting at saves work because any smaller proper multiple of already has a smaller prime factor. [ref].
For a complete run with , the only prime numbers at most are , since . Exclude one before starting; it is not a prime number. The four marking passes are:
  • : mark , removing 29 candidates.
  • : mark . The nine newly removed candidates are ; the even integers were already marked.
  • : mark . Only are newly removed.
  • : mark . Only is newly removed.
There are surviving prime numbers:
The next surviving candidate is , and , so no further marking pass is necessary. A prime number used for marking remains a candidate: starting at never marks itself.
Figure 1.
Four passes of the sieve of Eratosthenes through 60 leave seventeen prime numbers
. Blue cells are newly marked composite numbers; gray cells were removed earlier. White cells are candidates in the first three panels, and green cells are the final prime numbers. The outlined cell identifies the prime number used for that pass. One is excluded throughout. Details.
The saving from starting at is justified by the smaller multiplier: if with , then has a prime factor , so has already marked . For , the earlier multiples have already been marked using or . The first new possibility is .
For , only the prime numbers need marking passes. They remove all the composite numbers, leaving 25 prime numbers. The diagram colors each composite number by its smallest prime factor, so it shows which marking pass removes it first. The excluded integer one is shown separately.
Figure 2.
The sieve of Eratosthenes leaves 25 prime numbers among the integers from one to 100
. Each colored composite number is assigned to its smallest prime factor, one of . The green survivors are prime numbers; one is neither a prime number nor a composite number. Details.
Why does the algorithm work? A surviving candidate cannot be a composite number, since its smaller prime factor would already have removed it. Conversely, marking proper multiples never removes a prime number. Every composite number at most has a prime factor at most , so no later pass is needed. The sieve of Eratosthenes is useful when an entire bounded list is wanted; primality testing of one large integer is a different computational task.
The historical name is supported by a surviving primary account: Nicomachus, in Book I, chapter 13 of Introduction to Arithmetic, names Eratosthenes and describes separating prime numbers from composite numbers by marking multiples among the odd integers beginning with three. That passage documents the sieve tradition; the bounded algorithm above and its starting rule are the formulation explained here, rather than instructions quoted from Euclid's Elements. [ref]
Simple random walk on the integer line Created 2026-09-24 Updated 2026-10-14
A simple random walk on the integer line starts at and takes independent and identically distributed random variables as unit increments, with
The simple symmetric random walk has ; a biased random walk has . At or every step is deterministic, giving or respectively.
Count the rightward steps using indicator functions:
Thus the endpoint is a shifted and rescaled random variable with a binomial distribution. For a worked example, at the endpoint means exactly three rightward steps and one leftward step. There are possible orders, so its probability is , equal to in the fair case. More generally the binomial coefficient counts the orders, giving the exact probability mass function
In particular, the endpoint must have the same integer parity as : . For the support of a probability distribution is exactly . At only even integers in are reachable; at only odd integers are reachable. This restriction is easy to lose if one draws a smooth curve instead of discrete probability masses. The fair-walk counting argument is also presented in Grinstead and Snell, Introduction to Probability, section 12.1.
Figure 1.
Exact binomial endpoint probabilities for fair walks of 20 and 80 steps and a biased walk of 80 steps; only even endpoints are possible.
Details.
The endpoint identity and the binomial distribution give the expected value, variance, and standard deviation
A short direct check gives and , hence . Then apply linearity of expectation and the variance of a sum of independent random variables.
The absolute width and the width relative to the number of steps answer different questions. In the fair case the standard deviation grows from to , while shrinks from to . At , the standard deviation is , or times the fair width, and . Centering and dividing by each walk's own standard deviation gives, for ,
This rescaling equalizes the variances, not the entire probability distributions. The spacing between reachable endpoints is two, so its rescaled spacing is : approximately for the fair -step walk, for the fair -step walk, and for the biased -step walk.
The positions themselves are dependent. For , , where the second term is independent of . Their covariance is therefore
For example, in the fair case allows or , whereas allows or . Nevertheless the position process is a Markov chain: given its current position, the next fresh increment has no dependence on its past. Its transition probabilities are
These transition probabilities are the same at every time and every integer position: shifting both and by the same integer leaves unchanged. Thus the Markov property and independent increments coexist with dependent positions.
Two controlled walkers on the same connected undirected graph can each traverse one edge or wait in each unit-cost step. If they meet only by occupying the same vertex at the same time, their minimum meeting time is
where is the shortest path distance. A common meeting point after steps implies by the triangle inequality. Conversely, choose a middle vertex of a shortest connecting graph path; both walkers reach it within steps, and the earlier arrival waits. The wait is essential when the path length is an odd integer. This distance on the joint Cartesian product state space is a consistent heuristic: each joint move changes the walkers’ separation by at most two. Replacing by an obstacle-free Manhattan distance preserves admissible heuristic and consistent heuristic guarantees.
Take , the nonnegative integers, and , the positive integers. Choose the injections
Here is an inclusion map, while reaches only the positive even integers. In particular, is not a bijection: it misses every positive odd integer. Simply using the inverse function of on its image misses input zero.
The remedy is to follow the alternating injections starting at the missing input zero:
The subscripts distinguish an input in from an output in , even when their numerical values agree. The resulting subset of is . Its sequence of members satisfies and , giving by mathematical induction. Define the function
Figure 1.
A bijection moves only the sequence
. The upper row alternates the original injections and . Solid blue arrows are the chosen bijection on ; dashed gray arrows only continue the chain. Below, examples outside use and keep their numerical values. Every displayed number belongs to the explicitly constructed example. Details.
The image covers all the positive members of exactly once. The other inputs cover exactly once by staying fixed. These output sets are disjoint and their union is , proving that is a bijection. In particular, , , , while and .
For completeness, its inverse function is
The familiar bijection also works, but this example shows something more specific: the two chosen injections can repair the missing zero by moving only a sparse sequence of inputs. The repair never has to shift the entire set.
Subsequential limit Created 2026-10-14 Updated 2026-10-25
A subsequential limit of a sequence is a value approached by some subsequence with strictly increasing indices . For , the subsequences at even integers and odd integers give subsequential limits one and minus one. A finite value appearing among only finitely many initial terms does not become a subsequential limit merely by being a member of the image of a function represented by the sequence.
For a bounded sequence of real numbers, its subsequential limits form a nonempty bounded set that is also a closed set. The Bolzano-Weierstrass theorem guarantees nonemptiness, and its extreme values are the limit inferior and limit superior. The sequence in sparse peaks can determine a limit superior has the two subsequential limits zero and one, despite almost all indices in the natural density sense carrying zero.
Let the input alphabet be and let the output be , where independent noise is uniform on two distinct integers. Translating the output alphabet reduces the noise to , . The reachable output alphabet has size : it is the union of two three-element intervals shifted by .
For , every row of the transition matrix has conditional information entropy one bit, so . Input probabilities make the output uniform and attain one bit per use. For , the two translated input alphabets are disjoint and every output identifies its input. A uniform input then attains bits per use.
For , reflection symmetry and concavity of information entropy permit restricting to input probabilities . Conditional on output parity, outputs whose labels are even integers have probabilities and outputs whose labels are odd integers have probabilities . Consequently . Its strictly negative second derivative and stationary equation give and channel capacity . All three values follow from overlap of translated input alphabets, rather than from output alphabet size alone.
Triangular number Created 2026-10-14 Updated 2026-10-20
A triangular number counts rows of objects, with a nonnegative integer:
The first values are . The empty arrangement contributes zero, by the empty sum convention. Adding one more row gives the triangular number recurrence for . The row lengths form an arithmetic progression, while their running totals are triangular numbers.
Figure 1.
Two copies of six triangular rows form a rectangle of six rows and seven dots
. Details.
Pair the rows with a reversed copy: . There are such pairs, so two copies contain dots. Dividing by two proves the formula. This rectangle picture explains the factor one-half without requiring a formula for a long summation. For example, one hundred rows contain dots.
The same count appears whenever every pair of different objects must be considered once. Five participants make ten possible handshakes; five sensors have ten different pairwise comparisons; a complete graph on five vertices has ten edges. These are the triangular number pair-counting identity, with one fewer row than objects. The distinction prevents a common error: counts all pairs from six objects, whereas five objects give .
Figure 2.
Ten unordered pairs of five objects, and two consecutive triangular counts filling a square
. Details.
The triangular number square-complement identity says that two neighboring triangular numbers fill a square. Combining that identity with the one-row difference makes the difference of squares equal to . It leads to Nicomachus's theorem: the sum of the first cubes of numbers is the square of a number . A change in the way one groups objects exposes a relation between summation, multiplication and geometry.
This geometric view is already visible in Nicomachus's Introduction to Arithmetic by Nicomachus (Hahn teacher edition): Book II, Chapter 8 describes growing triangular rows, Chapter 12 combines successive triangular counts into squares, and Chapter 20 groups successive odd integers into cubes of numbers.[ref] The linked edition uses Martin Luther D'Ooge's translation, revised with modern teaching material by Nathanael Hahn. Our empty-row index is a modern convention; the historical passage starts from unity and calls three the first actual triangle.
A finite graph has a perfect matching if and only if the displayed inequalities hold, where counts the connected components of a graph with an odd integer number of vertices. The theorem is associated with William Thomas Tutte.[ref]
Necessity has a direct counting proof: each such component of must send at least one edge of a perfect matching to , and different components must use different vertices of . The sufficiency direction is the substantive content of the theorem. The criterion is useful because vertex degree and parity estimates can prove existence without constructing the perfect matching, as in the perfect matching theorem for a cubic graph with at most two bridges.