Skip to content

Instantly share code, notes, and snippets.

@vmfunc
Created July 12, 2024 21:47
Show Gist options
  • Save vmfunc/4aead5bea8473aa9590cc1b01475c965 to your computer and use it in GitHub Desktop.
Save vmfunc/4aead5bea8473aa9590cc1b01475c965 to your computer and use it in GitHub Desktop.
optimized pow10
#include <iostream>
#include <climits>
const static int longsize = sizeof(long) * CHAR_BIT;
constexpr const static long pow10[19] = {
1,
10,
100,
1000,
10000,
100000,
1000000,
10000000,
100000000,
1000000000,
10000000000,
100000000000,
1000000000000,
10000000000000,
100000000000000,
1000000000000000,
10000000000000000,
100000000000000000,
1000000000000000000
};
long getDigitsInNumber(long x) {
if (x == 0) return 1;
long t = ((longsize - __builtin_clzl(x)) * 1233) >> 12;
return t + (x >= pow10[t]);
}
int main() {
long x = 100;
std::cout << getDigitsInNumber(x) << std::endl;
return 0;
}
#include <iostream>
#include <climits>
const static long longsize = sizeof(long)*CHAR_BIT;
constexpr const static long pow10[20] = {
1,
10,
100,
1000,
10000,
100000,
1000000,
10000000,
100000000,
1000000000,
10000000000,
100000000000,
1000000000000,
10000000000000,
100000000000000,
1000000000000000,
10000000000000000,
100000000000000000,
1000000000000000000
};
long getDigitsInNumber(long x) {
long minDigits = ((__builtin_clzl(x) | (-longsize)) * -1233 >> 12);
return minDigits + (pow10[minDigits] <= x);
}
int main() {
long x = 100;
std::cout << x << std::endl;
return 0;
}
// lzcnt rax, rdi
// or rax, -64
// imul rax, rax, -1233
// shr rax, 12
// cmp rdi, qword ptr [8*rax + pow10]
// sbb rax, -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment