Created
July 12, 2024 21:47
-
-
Save vmfunc/4aead5bea8473aa9590cc1b01475c965 to your computer and use it in GitHub Desktop.
optimized pow10
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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