Algorithm Search⌘K

Algorithmintro

Hamilton's method

Also called largest remainder method, Hare-Niemeyer method.

Gives each party the integer part of its quota and the remaining seats to the parties with the largest fractional remainders.

Time
O(n log n) worst
Space
O(n) extra
Where
h = the number of seats; n = the number of states or parties
Properties
comparison baseddeterministiciterative
Origin
Alexander Hamilton, 1792

Hamilton's method apportions hh seats among states or parties in proportion to their populations or votes. Each one first gets the whole part of its exact share, its quota, and the few seats that are left go to those with the largest fractional parts. The result always stays within quota, and it is the closest integer vector to the quotas. But it can take a seat away from a state when the house grows (the Alabama paradox) or when the state grows faster than another.

In plain words

Work out the fair share of each state, which is usually not a whole number, for example 3.48 seats. Give each state the whole part of its share, here 3 seats. Some seats are still free, fewer than the number of states. Give them, one each, to the states whose shares were cut the most, that is, to the largest fractional parts. No state ends up more than one seat away from its fair share. The method is easy to explain and to check by hand.

The problem

The input is the populations p1,…,pn≥0p_1, \ldots, p_n \ge 0, integers with sum P>0P > 0, and the house size hh. The quota of state ii is qi=hpi/Pq_i = h p_i / P, its exact share, and ∑iqi=h\sum_i q_i = h. The output is integers ai≥0a_i \ge 0 with ∑iai=h\sum_i a_i = h. See the apportionment problem for the general setting and the other methods.

The method writes qi=⌊qi⌋+ϕiq_i = \lfloor q_i \rfloor + \phi_i with 0≤ϕi<10 \le \phi_i < 1, gives ⌊qi⌋\lfloor q_i \rfloor to every state and one more seat to each of the s=h−∑i⌊qi⌋s = h - \sum_i \lfloor q_i \rfloor states with the largest ϕi\phi_i. Ties go to the smallest index.

The algorithm

All arithmetic is on integers: ⌊hpi/P⌋\lfloor h p_i / P \rfloor is integer division, and the remainder ri=hpi mod Pr_i = h p_i \bmod P is PϕiP \phi_i, so it orders the states in the same way as ϕi\phi_i.

  1. HAMILTON(p, h) ▷ p = (p_1, ..., p_n), h seats
  2. 1P ← p_1 + ... + p_n
  3. 2for i ← 1 to n do a_i ← ⌊h p_i / P⌋; r_i ← h p_i mod P
  4. 3s ← h - (a_1 + ... + a_n) ▷ 0 ≤ s < n
  5. 4order the states by decreasing r_i, the smallest index among ties
  6. 5for each of the first s states i in this order do
  7. 6a_i ← a_i + 1
  8. 7return a

Line L2 gives the lower quotas and the remainders, line L3 counts the free seats, and lines L4 to L6 give them to the largest remainders.

Example

Four parties have 100000, 80000, 30000 and 20000 votes, so P=230000P = 230000, and h=8h = 8 seats are to be filled.

party votes quota qiq_i ⌊qi⌋\lfloor q_i \rfloor remainder rir_i seats
1 100000 3.478 3 110000 3
2 80000 2.783 2 180000 3
3 30000 1.043 1 10000 1
4 20000 0.696 0 160000 1

The lower quotas sum to 6, so s=2s = 2 seats are free. The two largest remainders are those of parties 2 and 4, and the result is (3,3,1,1)(3, 3, 1, 1). The Sainte-Lague method and the Huntington-Hill method give the same result here, and the D'Hondt method gives (4,3,1,0)(4, 3, 1, 0), which takes a seat from the smallest party.

Correctness

The proof shows that s=∑iϕis = \sum_i \phi_i, so 0≤s<n0 \le s < n, and that a state with ϕi=0\phi_i = 0 never gets an extra seat. So the seats sum to hh and each state gets ⌊qi⌋\lfloor q_i \rfloor or ⌈qi⌉\lceil q_i \rceil: the method satisfies quota. It also shows that the output minimizes ∑i(ai−qi)2\sum_i (a_i - q_i)^2 over all integer vectors with sum hh. A transfer of one seat from ii to jj changes this sum by 2(dj−di+1)2(d_j - d_i + 1), where d=a−qd = a - q, so in an optimum all did_i lie within 1 of each other, and the best choice of the extra seats is the one with the largest fractional parts.

Proof: Correctness and optimality of Hamilton's methodfull

Let p1,…,pn≥0p_1, \ldots, p_n \ge 0 be integers with P=∑ipi>0P = \sum_i p_i > 0, and let h≥0h \ge 0 be an integer. The quota of state ii is qi=hpi/Pq_i = h p_i / P, so ∑iqi=h\sum_i q_i = h. Write qi=⌊qi⌋+ϕiq_i = \lfloor q_i \rfloor + \phi_i with 0≤ϕi<10 \le \phi_i < 1.

Claim 1 (the integer form). Line L2 sets ai=⌊qi⌋a_i = \lfloor q_i \rfloor and ri=Pϕir_i = P \phi_i.

Proof. Division with remainder gives hpi=P⌊hpi/P⌋+(hpi mod P)h p_i = P \lfloor h p_i / P \rfloor + (h p_i \bmod P) with 0≤hpi mod P<P0 \le h p_i \bmod P < P. Divide by PP.

So ordering the states by rir_i is the same as ordering them by ϕi\phi_i, and the method needs no fractions.

Claim 2 (the number of extra seats). The number ss of line L3 is ∑iϕi\sum_i \phi_i, and 0≤s<n0 \le s < n. Moreover ss is less than the number of states with ϕi>0\phi_i > 0, unless s=0s = 0.

Proof. s=h−∑i⌊qi⌋=∑i(qi−⌊qi⌋)=∑iϕis = h - \sum_i \lfloor q_i \rfloor = \sum_i (q_i - \lfloor q_i \rfloor) = \sum_i \phi_i. Each ϕi\phi_i is in [0,1)[0, 1), so the sum of the positive ones is less than their number.

Claim 3 (output). The method returns integers ai≥0a_i \ge 0 with ∑iai=h\sum_i a_i = h and ⌊qi⌋≤ai≤⌈qi⌉\lfloor q_i \rfloor \le a_i \le \lceil q_i \rceil for every ii (the quota property).

Proof. Lines L5 and L6 add 1 to exactly ss of the ⌊qi⌋\lfloor q_i \rfloor, so the sum is ∑i⌊qi⌋+s=h\sum_i \lfloor q_i \rfloor + s = h. Each state gets ⌊qi⌋\lfloor q_i \rfloor or ⌊qi⌋+1\lfloor q_i \rfloor + 1. By Claim 2 and the order of line L4, a state that gets the extra seat has ri>0r_i > 0, so qiq_i is not an integer and ⌊qi⌋+1=⌈qi⌉\lfloor q_i \rfloor + 1 = \lceil q_i \rceil.

Claim 4 (least squares). Among all integer vectors b≥0b \ge 0 with ∑ibi=h\sum_i b_i = h, the output aa minimizes D(b)=∑i(bi−qi)2D(b) = \sum_i (b_i - q_i)^2. If the remainders rir_i are distinct, it is the only minimizer.

Proof. Let bb be a minimizer and di=bi−qid_i = b_i - q_i, so ∑idi=0\sum_i d_i = 0. Moving one seat from state ii to state jj changes DD by

(di−1)2−di2+(dj+1)2−dj2=2(dj−di+1).(d_i - 1)^2 - d_i^2 + (d_j + 1)^2 - d_j^2 = 2 (d_j - d_i + 1).

Let ii have the largest did_i and jj the smallest djd_j, and suppose di−dj>1d_i - d_j > 1. Then bi≥1b_i \ge 1: if bi=0b_i = 0, then di=−qi≤0d_i = -q_i \le 0, so every d≤0d \le 0 with sum 0, every d=0d = 0, and there is no gap. So the move is allowed, and it lowers DD, which is a contradiction. So a minimizer has max⁡idi−min⁡idi≤1\max_i d_i - \min_i d_i \le 1. Since the did_i sum to 0, min⁡idi≤0≤max⁡idi\min_i d_i \le 0 \le \max_i d_i, so every did_i is in [−1,1][-1, 1]. If some di=−1d_i = -1, then max⁡idi≤0\max_i d_i \le 0, so every di≤0d_i \le 0 with sum 0, and every di=0d_i = 0, a contradiction. In the same way no di=1d_i = 1. So ∣bi−qi∣<1|b_i - q_i| < 1, that is, bi=⌊qi⌋+xib_i = \lfloor q_i \rfloor + x_i with xi∈{0,1}x_i \in \{0, 1\}, xi=0x_i = 0 when ϕi=0\phi_i = 0, and ∑ixi=s\sum_i x_i = s.

For such a vector, D(b)=∑iϕi2+∑i:xi=1((1−ϕi)2−ϕi2)=∑iϕi2+∑i:xi=1(1−2ϕi)D(b) = \sum_i \phi_i^2 + \sum_{i : x_i = 1} \bigl((1 - \phi_i)^2 - \phi_i^2\bigr) = \sum_i \phi_i^2 + \sum_{i : x_i = 1} (1 - 2 \phi_i). This is smallest when the ss states with xi=1x_i = 1 are ss states with the largest ϕi\phi_i, which is the choice of lines L4 to L6. If the ϕi\phi_i are distinct, this choice is unique.

The same argument works for ∑i∣bi−qi∣t\sum_i |b_i - q_i|^t with any t≥1t \ge 1, since only the order of the ϕi\phi_i matters.

Claim 5 (the Alabama paradox). The method is not house monotone: with p=(3,3,1)p = (3, 3, 1), it gives (1,1,1)(1, 1, 1) for h=3h = 3 and (2,2,0)(2, 2, 0) for h=4h = 4.

Proof. For h=3h = 3 the quotas are 9/7,9/7,3/79/7, 9/7, 3/7: the integer parts are (1,1,0)(1, 1, 0), s=1s = 1, and the remainders 2/7,2/7,3/72/7, 2/7, 3/7 give the seat to state 3. For h=4h = 4 the quotas are 12/7,12/7,4/712/7, 12/7, 4/7: the integer parts are (1,1,0)(1, 1, 0), s=2s = 2, and the remainders 5/7,5/7,4/75/7, 5/7, 4/7 give the two seats to states 1 and 2.

Complexity

Line L2 takes O(n)O(n) operations on numbers of the size of hPh P. The sort of line L4 takes O(nlog⁡n)O(n \log n) comparisons, and the rest is O(n)O(n). A sort is not needed: a selection algorithm finds the ss-th largest pair (ri,−i)(r_i, -i) in O(n)O(n) worst-case time, by median of medians, and then one pass gives the extra seats. So the problem is solved in O(n)O(n) time, independent of hh. Extra space is O(n)O(n).

Properties

  • Quota. Each state gets its lower or its upper quota, by construction.
  • Least squares. The output minimizes ∑i(ai−qi)2\sum_i (a_i - q_i)^2, and also ∑i∣ai−qi∣t\sum_i |a_i - q_i|^t for every t≥1t \ge 1, among all apportionments.
  • Alabama paradox. With populations (3,3,1)(3, 3, 1), h=3h = 3 gives (1,1,1)(1, 1, 1) and h=4h = 4 gives (2,2,0)(2, 2, 0): the third state loses its seat when the house grows. See the Alabama paradox.
  • Population paradox. With h=5h = 5, populations (5,1,3)(5, 1, 3) give (3,0,2)(3, 0, 2), and populations (6,1,6)(6, 1, 6) give (2,1,2)(2, 1, 2). State 1 grew and lost a seat to state 2, which did not change.
  • New states paradox. Populations (8,1)(8, 1) with h=4h = 4 give (4,0)(4, 0). Add a state of population 3 and one seat for it: populations (8,1,3)(8, 1, 3) with h=5h = 5 give (3,1,1)(3, 1, 1), so the old states change their seats.
  • No divisor form. Hamilton's method is not a divisor method. By the Balinski-Young theorem, no method that satisfies quota is free of the population paradox.

Variants and improvements

  • Other quotas. Largest remainder methods for party lists divide the votes by a quota and give the remaining seats to the largest remainders. The Hare quota P/hP/h gives Hamilton's method. The Droop quota ⌊P/(h+1)⌋+1\lfloor P/(h + 1) \rfloor + 1 and the Imperiali quota P/(h+2)P/(h + 2) give fewer free seats, and with them the lower quotas can sum to more than hh.
  • The quota method. Balinski and Young (1975) gave a method that gives seats one at a time, as divisor methods do, but only to states that stay within upper quota. It satisfies quota and is house monotone, but it has the population paradox.
  • Divisor methods. The D'Hondt, Sainte-Lague and Huntington-Hill methods have no Alabama or population paradox, but they can violate quota.
  • Lotteries. A randomized method can give each state ⌊qi⌋\lfloor q_i \rfloor or ⌈qi⌉\lceil q_i \rceil seats with expected value exactly qiq_i. Gölz, Peters and Procaccia (2022) give one that is also house monotone.

When to use it

Use Hamilton's method when the rule must be easy to explain and each party must get its quota rounded up or down. It suits a fixed house and a single election. It is a poor choice when the house size or the populations change over time and the changes must look fair, as in a census apportionment, because of the Alabama and population paradoxes.

Pitfalls

  • Floating point. Computing hpi/Ph p_i / P in floating point can misorder two close remainders or even get the floor wrong. Use integer division and the remainder hpi mod Ph p_i \bmod P.
  • Ties. Two states with equal remainders can compete for the last seat. A law must say how to break the tie; this page uses the smallest index.
  • Zero populations. A state with pi=0p_i = 0 has remainder 0 and never gets a seat. Do not let it win a tie at remainder 0; with the order of line L4 it cannot, because ss is less than the number of positive remainders.
  • The quota is not the result. The method stays within quota, but it is not monotone in hh. Do not assume that a larger house keeps the old seats.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

hamilton_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hamilton-method/. The authors are listed in prov/S01MQ4.jsonl.

from fractions import Fraction
from typing import Sequence


def quotas(populations: Sequence[int], h: int) -> list[Fraction]:
    """Return the exact quotas h p_i / P."""
    total = sum(populations)
    return [Fraction(h * p, total) for p in populations]


def hamilton_method(populations: Sequence[int], h: int) -> list[int]:
    """Apportion h seats by Hamilton's method (largest remainders).

    populations are nonnegative integers with a positive sum. Each state gets the integer
    part of its quota h p_i / P, and the s seats that are left go to the s states with the
    largest remainders, the smallest index among ties. All arithmetic is on integers: the
    remainder of state i is h p_i mod P, which is P times the fractional part of its quota.
    """
    if h < 0 or any(p < 0 for p in populations) or sum(populations) <= 0:
        raise ValueError("need h >= 0, populations >= 0 and a positive total")
    n = len(populations)
    total = sum(populations)  # @line L1
    a = [h * p // total for p in populations]  # @line L2
    r = [h * p % total for p in populations]
    s = h - sum(a)  # @line L3
    order = sorted(range(n), key=lambda i: (-r[i], i))  # @line L4
    for i in order[:s]:  # @line L5
        a[i] += 1  # @line L6
    return a  # @line L7
test_hamilton_method.py 101 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hamilton-method/. The authors are listed in prov/S01MQ4.jsonl.

import random
import unittest
from fractions import Fraction

from hamilton_method import hamilton_method, quotas


def compositions(h, n):
    """Yield every list of n nonnegative integers with sum h."""
    if n == 1:
        yield [h]
        return
    for x in range(h + 1):
        for rest in compositions(h - x, n - 1):
            yield [x] + rest


def cost(a, q):
    return sum((x - y) ** 2 for x, y in zip(a, q))


def by_fractions(populations, h):
    """A second implementation with Fraction quotas and their fractional parts."""
    q = quotas(populations, h)
    a = [x.numerator // x.denominator for x in q]
    frac = [x - y for x, y in zip(q, a)]
    for i in sorted(range(len(q)), key=lambda i: (-frac[i], i))[: h - sum(a)]:
        a[i] += 1
    return a


class TestCheckValues(unittest.TestCase):
    def test_four_parties(self):
        self.assertEqual(hamilton_method([100000, 80000, 30000, 20000], 8), [3, 3, 1, 1])

    def test_alabama_paradox(self):
        self.assertEqual(hamilton_method([3, 3, 1], 3), [1, 1, 1])
        self.assertEqual(hamilton_method([3, 3, 1], 4), [2, 2, 0])

    def test_population_paradox(self):
        self.assertEqual(hamilton_method([5, 1, 3], 5), [3, 0, 2])
        self.assertEqual(hamilton_method([6, 1, 6], 5), [2, 1, 2])

    def test_new_states_paradox(self):
        self.assertEqual(hamilton_method([8, 1], 4), [4, 0])
        self.assertEqual(hamilton_method([8, 1, 3], 5), [3, 1, 1])

    def test_errors(self):
        for p, h in (([0, 0], 3), ([1, -1, 2], 2), ([1, 2], -1)):
            with self.assertRaises(ValueError):
                hamilton_method(p, h)


class TestProperties(unittest.TestCase):
    def test_sum_and_quota(self):
        rng = random.Random(21)
        for _ in range(3000):
            n = rng.randint(1, 8)
            p = [rng.randint(0, 1000) for _ in range(n)]
            if sum(p) == 0:
                continue
            h = rng.randint(0, 40)
            a = hamilton_method(p, h)
            self.assertEqual(sum(a), h)
            for x, q in zip(a, quotas(p, h)):
                self.assertTrue(q.numerator // q.denominator <= x <= -(-q.numerator // q.denominator))
            self.assertEqual(a, by_fractions(p, h))

    def test_least_squares_by_brute_force(self):
        rng = random.Random(22)
        for _ in range(250):
            n = rng.randint(1, 4)
            p = [rng.randint(1, 60) for _ in range(n)]
            h = rng.randint(0, 9)
            q = quotas(p, h)
            a = hamilton_method(p, h)
            best = min(cost(b, q) for b in compositions(h, n))
            self.assertEqual(cost(a, q), best)
            r = [x - x.numerator // x.denominator for x in q]
            if len(set(r)) == n:
                self.assertEqual([b for b in compositions(h, n) if cost(b, q) == best], [a])

    def test_alabama_paradox_is_common(self):
        found = 0
        for p in ([3, 3, 1], [5, 5, 2], [7, 6, 2]):
            for h in range(1, 20):
                a, b = hamilton_method(p, h), hamilton_method(p, h + 1)
                if any(y < x for x, y in zip(a, b)):
                    found += 1
        self.assertGreater(found, 0)

    def test_quota_sums(self):
        self.assertEqual(sum(quotas([100000, 80000, 30000, 20000], 8)), 8)
        self.assertEqual(quotas([3, 3, 1], 4), [Fraction(12, 7), Fraction(12, 7), Fraction(4, 7)])


if __name__ == "__main__":
    unittest.main()

History

Alexander Hamilton proposed the method for the first apportionment of the US House after the census of 1790. Congress passed it in 1792, and George Washington vetoed the bill, his first veto; Jefferson's method was used instead. The method came back in 1850, proposed by Samuel Vinton, and was used with changes until the census of 1900. In 1880 C. W. Seaton, the chief clerk of the Census Office, found that Alabama would get 8 seats in a house of 299 and only 7 in a house of 300, the paradox that now carries its name. The population paradox appeared around 1900, and the new states paradox when Oklahoma joined in 1907. In Europe the same rule is called the Hare-Niemeyer method, and Germany used it for the Bundestag from 1987 to 2005. Balinski and Young (1975, 1982) studied it in their theory of apportionment.

References

  1. Michel L. Balinski and H. Peyton Young, Fair Representation: Meeting the Ideal of One Man, One Vote, 2nd edition, Brookings Institution Press, 2001, Chapter 3 (The Methods of Jefferson and Hamilton) and Chapter 5 (Paradoxes)
  2. M. L. Balinski and H. P. Young, The quota method of apportionment, American Mathematical Monthly 82(7) (1975), 701-730, the quota property and house monotonicity, and why Hamilton's method has the first and not the second
  3. Paul Gölz, Dominik Peters and Ariel D. Procaccia, In this apportionment lottery, the House always wins, Operations Research 74(1) (2026), 390-407, Section 3.1, Theorem 1: no deterministic method satisfies quota and population monotonicity

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example