KatInterview

Balanced Digit Sum Across All Bases

Math & Bit ManipulationAuto-graded · 18 test cases
MediumAuto-gradedMath & Bit Manipulationmathbit manipulationbase conversion

Last updated

Tests understanding of base conversion by summing digits of a number across every base from 2 to b and checking whether each base yields a digit sum equal to a target value.

Balanced Digit Sum Across All Bases

Given a positive integer n and a target digit sum t, a base b (where b >= 2) is called balanced for n if the sum of the digits of n when written in base b equals exactly t.

Write a function that, given n, t, and an upper bound b_max, returns the list of all balanced bases for n in the range [2, b_max], in ascending order.

How digit-sum in base b works

To find the digit sum of n in base b:

  1. Repeatedly take n % b to get the least-significant digit.
  2. Replace n with n // b.
  3. Sum all collected digits until n becomes 0.

For example, n = 13 in base 3 is 111 (since 1·9 + 1·3 + 1 = 13), so its digit sum in base 3 is 3.

Special case: base ≥ n + 1

When b > n, the representation of n in base b is just the single digit n itself (since n < b). In this situation the digit sum equals n. For all such bases the digit sum is identical, so they are either all balanced (if n == t) or none of them are. Your function should only return the single value b_max as the representative of this group if n == t and b_max >= n + 1; do not list every base from n+1 to b_max.

More precisely: if n == t and b_max >= n + 1, include exactly the value max(n + 1, 2) in the results (representing all bases ≥ n+1 by the smallest such base that is ≤ b_max). Do not include any other values ≥ n+1.

Wait — let's simplify the rule to avoid ambiguity:

Return exactly those bases b in [2, min(b_max, n)] for which the digit sum of n in base b equals t, PLUS, if n == t and b_max >= n + 1, also include n + 1 in the result.

(When n == 1, base 2 gives digit representation 1 with digit sum 1, handled by the general loop; and n+1 = 2 is already in range so no special case needed beyond the formula.)

Constraints

  • 1 <= n <= 10^6
  • 0 <= t <= 200
  • 2 <= b_max <= 10^6
  • The returned list must be in ascending order.

Examples

Example 1

Input: balanced_bases(13, 3, 20)

Output: [2, 3, 6, 11]

Example 2

Input: balanced_bases(12, 3, 15)

Output: [4, 10]

Example 3

Input: balanced_bases(7, 7, 10)

Output: [8]

Hints

Hint 1

For each base b from 2 to min(b_max, n), compute the digit sum using repeated mod and integer division — this is O(log_b(n)) per base.

Hint 2

The total work across all bases 2..n is O(n) overall because sum of log_b(n) for b=2..n is O(n) by the integral approximation.

Hint 3

Handle the b > n edge case separately: every such base gives digit sum exactly n, so it is balanced if and only if t == n; represent this whole group by the single base n+1 if it is within b_max.