templates/math-utilities.cpp
compilable
$cat templates/math-utilities
Math Utilities
Base conversion, range summation, counting/summing multiples, and log base.
#base-conversion#summation#multiples#math
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#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
ll. Handles upper/lowercase and negatives