By the time print(n) is called, record has evaluated divisors(i) once for every . In the unit-cost model, the total number of remainder tests is
The record values comparisons add only work, and output is cheap by assumption. The elapsed time is . This measures time to reach a given highly composite number, rather than time as a function of the number of printed records.
The second procedure should reach large outputs faster, because the first makes exactly expensive MOD operations when processing argument , whereas the second tries only up to the square root of a shrinking residual, with at most successful DIV operations. Each successful division also requires a successful MOD test; each outer iteration adds one final unsuccessful MOD test. Thus its expensive-operation count is per argument, and at most cumulatively through argument , compared with for direct counting.
The speedup is not an assertion that every single call uses fewer divisions: for , the second code makes three MOD tests and two DIV operations, while the first makes four MOD tests. Small constant costs can go either way. The many small prime factors in highly composite numbers also shrink the residual early, which often helps further; the cumulative comparison includes every preceding argument, not only the printed records.
Use a strict record test; tying the previous record is not enough:
def emitHighlyComposite(): Unit = {
  var candidate = 1
  var best = 0
  while (true) {
    val count = divisors(candidate)
    if (count > best) {
      emit(candidate)
      best = count
    }
    candidate += 1
  }
}
At the start of an iteration, best is the maximum divisor count among the positive integers below candidate, taking the maximum of the empty family as zero. The already emitted values are exactly the highly composite numbers in that range, in increasing order. The next count exceeds best precisely when this candidate is a new strict record. Updating the record and advancing the candidate preserves both assertions. The program deliberately has no termination requirement; integer overflow in this unbounded enumeration is ignored as directed by the source.
Srinivasa Ramanujan 2026-11-05
Srinivasa Ramanujan developed results in number theory, including the study of highly composite numbers: positive integers having more divisors than every smaller positive integer.[ref]
His analysis connects record values of the divisor function with prime factorization. Prime exponents must be arranged in nonincreasing order as the primes increase: swapping an inverted pair would produce a smaller integer with the same divisor count, contradicting the record property. For example, has six positive divisors. The subject turns irregular arithmetic data into a constrained optimization problem.[ref]