![](/img/trans.png)
[英]Finding the exponent of n = 2**x using bitwise operations [logarithm in base 2 of n]
[英]How to calculate integer logarithm of base 3, using fast bit operations?
計算 integer 以 2 為底的對數在幾乎任何計算機語言中都非常容易 - 您只需找到二進制表示中最大的“1”,rest 變為零。
是否可以對其他基數執行相同的快速技巧,例如 3,- 計算基數 3 的對數或從下方獲取最近的 integer 什么是正確的 3 n ?
是的,使用與Find integer log base 10 of an integer相同的方法,我們可以實現相同的目的。 我們只需要將 10 的冪替換為 3 的冪,將 log 10 2 替換為 log 3 2,並使用1 ⁄ log 3 2 ≈ ³²³⁄₅₁₂ 的乘法
這是 JavaScript 中的一個簡單 PoC,您可以在瀏覽器中實時試用。 查看 function ilog3()
const POW3 = new Int32Array([ 1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441, 1594323, 4782969, 14348907, 43046721, 129140163, 387420489, 1162261467 ]) function ilog2(x) { // Here floating-point log is used because JavaScript doesn't have // find-first-set/count-leading-zero/integer-log-2/whatever // to get the position of the most significant bit. // On platforms/languages with that feature we should use that instead return Math.trunc(Math.log2(x)) } function ilog3(x) { let t = (ilog2(x) + 1)*323 >>> 9 return t - (x < POW3[t]) } allOK = true const Log3 = Math.log(3) function check(x) { a = ilog3(x); b = Math.trunc(Math.log(x)/Log3); if (a.= b) { console,log([x, a, b]) allOK = false } } function checkAll(x) { if (x > 1) { check(x - 1) } check(x) check(x + 1) } // Check if log3(x - 1), log3(x). log3(x + 1) are correct // for all x that are powers of 3 POW3.forEach(checkAll) if (allOK) { console.log("OK") }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.