guest@itl:~/home/utilities$
templates/math-utilities.cpp
compilable
$cat templates/math-utilities

Math Utilities

Base conversion, range summation, counting/summing multiples, and log base.

[Utilities]|
Jul 9, 2026
|explanatory_notes.md|
#base-conversion#summation#multiples#math
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
#include <bits/stdc++.h>
using namespace std;
using ll = long long;

string decimalToBase(ll n, int base) {
    if (n == 0) return "0";
    string digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    string res;
    bool neg = n < 0;
    if (neg) n = -n;
    while (n > 0) { res += digits[n % base]; n /= base; }
    if (neg) res += '-';
    reverse(res.begin(), res.end());
    return res;
}

ll baseToDecimal(const string &s, int base) {
    ll res = 0;
    int start = 0;
    bool neg = false;
    if (s[0] == '-') { neg = true; start = 1; }
    for (int i = start; i < (int)s.size(); i++) {
        int d = isdigit(s[i]) ? s[i] - '0' : toupper(s[i]) - 'A' + 10;
        res = res * base + d;
    }
    return neg ? -res : res;
}

ll summation(ll l, ll r) {
    if (l > r) swap(l, r);
    return r * (r + 1) / 2 - (l - 1) * l / 2;
}

ll countMultiples(ll a, ll b, ll c) {
    return b / c - (a - 1) / c;
}

ll sumMultiples(ll a, ll b, ll c) {
    ll lo = (a + c - 1) / c;
    ll hi = b / c;
    if (lo > hi) return 0;
    return c * summation(lo, hi);
}

double logBase(ll a, int b) {
    return log((double)a) / log((double)b);
}
47 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)

Math Utilities

Functions

  • decimalToBase(n, base) — converts integer to string in given base (223636). Handles zero and negatives

  • baseToDecimal(s, base) — parses string in given base back to ll. Handles upper/lowercase and negatives

  • summation(l, r) — sum of integers from ll to rr:
  • sum(l,r)=r(r+1)2(l1)l2\text{sum}(l, r) = \frac{r(r+1)}{2} - \frac{(l-1) \cdot l}{2}

  • countMultiples(a, b, c) — count of multiples of cc in [a,b][a, b]:
  • b/c(a1)/c\lfloor b/c \rfloor - \lfloor (a-1)/c \rfloor

  • sumMultiples(a, b, c) — sum of multiples of cc in [a,b][a, b], using summation scaled by cc

  • logBase(a, b)logb(a)\log_b(a) as double. For exact checks, use isPerfectPower instead
  • When to Use

  • Base conversion, digit manipulation in non-decimal bases

  • Arithmetic series, range sums without loops

  • "How many in [l,r][l, r] divisible by kk" type problems
  • Complexity

  • decimalToBase — O(logbasen)O(\log_{\text{base}} n)

  • baseToDecimal — O(s)O(|s|)

  • All others — O(1)O(1)