KatInterview

Sum of Digits Across All Bases from 2 to K

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

Last updated

Tests ability to repeatedly convert an integer into multiple bases and accumulate digit sums, combining base-conversion mechanics with modular arithmetic.

Sum of Digits Across All Bases

Given a positive integer n and an integer k (with k >= 2), compute the total digit sum of n when written in every base b for b = 2, 3, 4, …, k.

More precisely, for each base b from 2 to k (inclusive):

  1. Express n in base b (using the standard greedy algorithm: repeatedly divide by b and collect remainders).
  2. Sum all the digits of that base-b representation.

Return the grand total — the sum of all per-base digit sums.

Notes

  • Digit values in any base are always in the range [0, b-1]; they are the remainders when you repeatedly divide by b.
  • When n = 0, every base representation is just "0", so each base contributes 0 to the total.
  • When k < 2, there are no bases to process; return 0.

Constraints

  • 0 <= n <= 10^9
  • 0 <= k <= 10^6

Examples

Example 1

Input: sum_of_digits_all_bases(10, 4)

Output: 8

Example 2

Input: sum_of_digits_all_bases(0, 10)

Output: 0

Example 3

Input: sum_of_digits_all_bases(7, 2)

Output: 3

Hints

Hint 1

For each base b, you can extract digits by repeatedly taking n % b and then doing n //= b until n becomes 0 — this is the standard base-conversion loop.

Hint 2

The digit sum for base b is just the sum of all remainders collected during that loop. No need to store the digits as a string.

Hint 3

When k < 2 or n == 0, handle as special cases: n == 0 always contributes 0 per base, and k < 2 means no bases to iterate.