KatInterview

Balanced-Radix Digital Root Collision Finder

Math & Bit ManipulationAuto-graded · 17 test cases
HardAuto-gradedMath & Bit Manipulationmathbit manipulationbase conversion

Last updated

Tests mastery of base conversion and number theory by finding all integers in a range whose digital roots are identical across two different bases.

Balanced-Radix Digital Root Collision

The digital root of a positive integer n in base b is computed by repeatedly summing the digits of n (written in base b) until a single digit remains. Formally:

  • Write n in base b.
  • Sum all its digits to get s.
  • If s >= b, repeat with s.
  • The process terminates when the result is a single base-b digit (i.e., a value in [1, b-1]).

For example, n = 255, b = 16:

  • 255 in base 16 is FF, digit sum = 15 + 15 = 30.
  • 30 in base 16 is 1E, digit sum = 1 + 14 = 15.
  • 15 is a single hex digit → digital root = 15.

There is a well-known closed-form: for n > 0 and base b, the digital root equals 1 + ((n - 1) % (b - 1)).


Task

Given integers lo, hi, b1, and b2 (with b1 != b2), return a sorted list of all integers n in the closed interval [lo, hi] such that:

digital_root(n, b1) == digital_root(n, b2)

These are called collision integers for the two bases.

The returned list must be sorted in ascending order.

Constraints

  • 1 <= lo <= hi <= 2000
  • 2 <= b1 < b2 <= 36
  • b1 != b2
  • The answer may be empty.
  • You may assume hi - lo <= 2000.

Examples

Example 1

Input: find_digital_root_collisions(1, 20, 2, 3)

Output: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

Example 2

Input: find_digital_root_collisions(1, 50, 10, 16)

Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 46, 47, 48, 49, 50]

Example 3

Input: find_digital_root_collisions(100, 130, 3, 5)

Output: [101, 102, 105, 106, 109, 110, 113, 114, 117, 118, 121, 122, 125, 126, 129, 130]

Hints

Hint 1

The digital root of n in base b (for n > 0) has a one-line closed form using modular arithmetic — no need to repeatedly convert and sum digits.

Hint 2

The collision condition dr(n, b1) == dr(n, b2) becomes an equation mod (b1-1) and mod (b2-1). Think about what values of n satisfy both simultaneously using the Chinese Remainder Theorem or direct enumeration.

Hint 3

Once you derive which residues mod lcm(b1-1, b2-1) produce collisions, you can iterate over the range [lo, hi] very efficiently — but a direct O(hi - lo) scan with the closed-form formula is also fast enough.