Log base 10 in speedcrunch6/22/2023 ![]() The maximum you can save with the runtime calculation are 10 bytes of RAM, but it is usually temporary so it is not worth it. The maximum number of bytes needed for a 32-bit int in base 10 is 10 digits, negative sign and null terminator for 12 chars. ![]() add 1 and you get the number of digits.īut you do not need to do this at runtime. It comes exactly from the fact that log10(1) = log10(10⁰) = 0Īnd all numbers between 10 and 100 have their logarithms between 1 and 2 so if you floor the logarithm for any two digit number you get 1. In principle, you get the number of digits in base 10 by taking the base-10 logarithm and flooring and adding 1. It uses a very complex calculation that happens at runtime, to save a couple bytes of temporary storage. (The extra char is for the NUL that terminates the string.) floor(log10(10000))+2 correctly returns 6.Ī 4-digit number such as 4567 will be between 1,000 (inclusive) and 10,000 (exclusive), so it will be between 10 3 (inclusive) and 10 4 (exclusive), so log 10(4567) will be between 3 (inclusive) and 4 (exclusive).Īs such, floor(log10(num))+1 will return number of digits needed to represent the positive value num in decimal.Īs such, floor(log10(num))+2 will return the amount of memory needed to store the decimal representation of the positive integer num as a string. ![]() The two formulas presented above are equal except for numbers which are exact powers of 10, in which case the former version returns one less than the desired number.įor example, 10,000 requires 6 bytes, yet ceil(log10(10000))+1 returns 5. The code is attempting to determine the amount of memory needed to store the decimal representation of the positive integer num as a string. Ceil(log10(num))+1 is incorrectly being used instead of floor(log10(num))+2.
0 Comments
Leave a Reply. |