Divide the divisibility relation by to obtain . Since , multiplication by the modular multiplicative inverse gives . Therefore all integer solutions are , .
Take . These are four distinct positive integers and . Their products are and , whose difference is , so . Here the correct reduced modulus is , and indeed . The example illustrates why cancelling a noninvertible factor may change the modulus in modular arithmetic.
Let , , and . The preceding part gives . The integer congruence on the left is equivalent toBy Euclid's lemma, coprimality of and makes this equivalent to . The reverse implication is also immediate by multiplying a divisibility relation by . ThereforeThis is cancellation of a common factor in a congruence. The printed equality sign in the right-hand expression is interpreted as equality of residue classes, hence the displayed integer congruence. Ordinary equality of the integers would be false: the following example has .
Let , and write , with positive integers . If an integer divided both and , then would divide both and , contradicting the maximality of their greatest common divisor . Thus . Equivalently, Bézout's identity for can be divided by to express as an integer combination of .
The contrapositive is that an integer perfect square has residue or modulo . Let for an integer . If is an even number, then . If is an odd number, then . These exhaust the possible parities of an integer. Thus a residue of or excludes being a perfect square, as required by the contrapositive.
Suppose, for a proof by contradiction, that an integer is both an even number and an odd number. Then and for some integers . Subtracting yields . The left side is an integer, while is not. This contradiction proves that no integer is both even and odd.
Fix any seven-element subset . Its power set supplies pigeons. Map each subset to its integer sum. Since the elements are positive, all such sums lie between and . The latter is at most the sum of the seven largest available elements,There are therefore at most possible sums, fewer than the subsets. The pigeonhole principle forces two distinct subsets to have the same sum. Every seven-element subset has the two-sum property. This is the subset-sum pigeonhole bound. The weaker estimate would also suffice, since .
The number isA direct search over every -element subset must inspect candidates. Testing one candidate by generating its subset sums creates values; storing previously seen sums detects a collision. Generating them incrementally needs arithmetic operations, or for the straightforward independent calculation of each sum. Thus the simple overall search has cost on the scale of , apart from integer-arithmetic and data-structure costs.
The important time complexity distinction is that fixed gives polynomial growth in , of degree , but this can still become impractically large. If increases with , both the candidate count and the internal power set can grow exponentially. For example, near the binomial coefficient is already exponentially large. An exhaustive implementation can therefore encounter a combinatorial explosion; the fixed- estimate must not be described as exponential in .
For , independence givesThe initial factor accounts for the shift by one; substituting accounts for doubling the random variable. Its support consists of positive odd integers.
The independent random variables have a product joint probability mass function. For integers ,It is zero for all other pairs. The factors are the respective Poisson distribution masses, with the product justified by independence.
Conditioning on has positive probability exactly when for an integer . This is the same event as . The addition of independent Poisson random variables gives a Poisson distribution with parameter for the sum. Therefore, for ,Thus . The case is a constant zero random variable. For even, nonpositive, or noninteger , the conditioning event has zero probability, so an event-conditional probability distribution is not specified by the quotient formula. This is a two-component case of Poisson-multinomial conditioning.
Insert the Poisson distribution probability generating function into the preceding bound:For fixed , differentiate the exponent with respect to . Its derivative is , and its second derivative is , so its unique minimum occurs at . At that value,ConsequentlyThis Chernoff bound remains valid for noninteger positive thresholds ; the event is then the same as exceeding or equalling its integer ceiling.
Because , the function is increasing and nonnegative. Thus . Applying Markov's inequality to the nonnegative random variable , whose expected value is finite by assumption, yieldsUnder the usual probability generating function convention takes nonnegative integer values. The argument itself works for any real random variable if is understood as the finite expected value .
There are three unnumbered cases inside this leaf.
For the nine-child recurrence, a recursion tree has subproblems of size about . There are constant-size leaves, and the total unit work over earlier levels is a geometric sum of the same order. Hence . This is also the first case of the master theorem, since and the additive work is constant.
For the decrementing recurrence, summing from the supplied base at three givesso here as well. Values at the smaller base indices remain one as specified.
For the recurrence that squares its recursive result, set . Then above the base range. LetAfter expansions, , giving the exact answerFor powers of two this is . For arbitrary positive integer , the exact values form plateaux: , while . In general . It is not uniformly over integer : near the top of a plateau the exponent is closer to . Keeping the integer halving is essential; the ordinary linear master theorem does not apply to squaring .
Let again be the total. Reject unless is divisible by three, and put . Define to mean that the first occurrences can be assigned to three groups so that the first two groups have sums and . Their third sum is already determined by the processed list prefix sum minus , so it need not be stored as another coordinate.
Initialize true and all other states false. For each reachable state, assign the next occurrence to exactly one group:The three transitions put the occurrence in the third, first or second group, respectively. Using a fresh layer prevents reusing it. Conversely, deleting the last occurrence from any valid list prefix assignment leaves exactly one predecessor state, so induction proves completeness as well as soundness. At the final state , the third sum is , giving precisely the required disjoint partition.
threeEqualParts(A):
S = sum of A
if S mod 3 != 0: return false
h = S/3
D[0..h,0..h] = false
D[0,0] = true
for each indexed entry a in A:
Next[0..h,0..h] = false
for x from 0 to h:
for y from 0 to h:
if D[x,y]:
Next[x,y] = true
if x+a <= h: Next[x+a,y] = true
if y+a <= h: Next[x,y+a] = true
D = Next
return D[h,h]There are states per layer and a constant number of transitions per state. Thus the time is , and rolling layers use space for nonempty inputs. The source mentions an additional integer in this part, but it does not occur in the stated equal-partition condition; the required target is determined by . Empty groups are allowed by the stated subset formulation.
Maintain opposite signs at the endpoints, rather than assuming that the polynomial is monotone:
def floorRoot(X: Int): Int = {
require(X > 0 && eval(0.0) <= 0.0 && eval(X.toDouble) > 0.0)
var lo = 0
var hi = X
while (hi - lo > 1) {
val mid = lo + (hi - lo) / 2
if (eval(mid.toDouble) <= 0.0) lo = mid
else hi = mid
}
lo
}The loop invariant is and . Both branches preserve those signs, even when there are other roots of a polynomial or sign reversals elsewhere. When the interval width exceeds one, the midpoint is strictly between its endpoints, so the positive integer loop variant
hi - lo strictly decreases. On exit hi == lo + 1, giving the required postcondition . Continuity establishes a root of a polynomial between those adjacent integers, possibly at the left endpoint.The width is at most halved with rounding upwards, so there are at most midpoint evaluations, plus two endpoint evaluations in the precondition check. The midpoint expression avoids adding two large endpoints. The explicit positive upper-bound precondition supplies the interval order assumed in the question. For the literal computed-
eval contract, the same proof holds provided evaluated midpoints are not NaN; identifying its bracket with the real polynomial additionally requires trustworthy evaluation signs.First find a sign bracket by exponential search, then bisect that bracket without evaluating its endpoints again:
def floorRoot(): Int = {
require(eval(0.0) < 0.0)
var lo = 0
var hi = 1
while (eval(hi.toDouble) <= 0.0) {
lo = hi
require(hi <= Int.MaxValue / 2, "doubling bound exceeds Int range")
hi *= 2
}
while (hi - lo > 1) {
val mid = lo + (hi - lo) / 2
if (eval(mid.toDouble) <= 0.0) lo = mid
else hi = mid
}
lo
}For the first while loop the loop invariant is , with
hi a positive power of two, and either or . Every previously tested power of two has nonpositive value. Let be the least nonnegative integer for which . It exists by the positive leading coefficient. If the current upper endpoint is , a mathematical loop variant is while the guard holds; the next doubling decreases it by one. The first while loop's postcondition is . The second while loop has exactly the invariant, variant and adjacent-integer postcondition established in part c.There are evaluations at powers of two. If , the final bracket has width and takes exactly midpoint evaluations. Including the initial sign check, the total is evaluations for , and two for . Thus evaluation cost is for the first positive dyadic bound ; it is not a claim about the first positive root of a polynomial when the polynomial is nonmonotone.
The mathematical argument uses unbounded integer endpoints and reliable signs. The guarded
Int implementation requires the successful dyadic bound to fit in Int; otherwise it explicitly fails rather than wrapping to a negative bound. The coefficient assumptions alone cannot guarantee that a requested integer result fits a fixed-width type. Floating-point overflow or unreliable signs likewise need a wider or certified evaluator for a fully general implementation.Use two finite integer lists , with the head of each list representing its stack top. Initially both are empty. A suitable abstract object interface is
trait DoubleStack {
def pusha(x: Int): Unit
def pushb(x: Int): Unit
def popa: Int
def popb: Int
def isEmptya: Boolean
def isEmptyb: Boolean
}For the unbounded abstract data type, each push has no logical precondition. The postcondition of
pusha(x) is and ; pushb(x) symmetrically gives and . The precondition of popa is , and its postcondition is return value , new state , and unchanged . The specification for popb exchanges . Each emptiness query leaves both lists unchanged and returns exactly whether its corresponding list is empty.These frame conditions matter: an operation on one stack must preserve the other, not merely produce the right return value.
The implementation maintains the two boundaries from part b:
class ArrayDoubleStack(val MAX: Int) extends DoubleStack {
require(MAX >= 0)
private val data = new Array[Int](MAX)
private var left = 0
private var right = MAX
def isEmptya: Boolean = left == 0
def isEmptyb: Boolean = right == MAX
def pusha(x: Int): Unit = {
require(left < right, "double stack is full")
data(left) = x
left += 1
}
def pushb(x: Int): Unit = {
require(left < right, "double stack is full")
right -= 1
data(right) = x
}
def popa: Int = {
require(left > 0, "stack a is empty")
left -= 1
data(left)
}
def popb: Int = {
require(right < MAX, "stack b is empty")
val answer = data(right)
right += 1
answer
}
}Initialization gives empty abstract lists. Each push consumes one free position next to the appropriate top; each pop returns that top and releases its position. The guards preserve the ordering of the two boundaries and prevent invalid indexing. The abstraction function shows directly that the untouched stack is unchanged. Keeping
data private prevents clients from violating the representation invariant; this strengthens encapsulation relative to a publicly exposed implementation field without changing the six required operations.All six operations run in time, with a fixed array of
MAX integers and constant extra state. Creating and zero-initializing the array takes time, outside those operation bounds. Capacity zero gives a valid always-empty bounded structure whose pushes fail their precondition.A sentinel node supplies a permanent predecessor for the first real node. Inserting or deleting at the front then uses the same
predecessor.next update as an interior operation. Its datum is not a multiset element: the chosen extreme integer is merely unused sentinel data.A representation invariant requires a nonnull fixed header, a finite acyclic chain starting at
bagHeader.next, and exclusion of the header from that chain. Each node identity occurs once, although different nodes may have equal data. Representation links are owned by the implementation, so outside mutation cannot alter them unexpectedly.