Skip to content

Commit d64e4fb

Browse files
dev-madhurendramadhuredra
andauthored
feat: added log2 method implementation (TheAlgorithms#175)
Co-authored-by: madhuredra <[email protected]>
1 parent 9843df6 commit d64e4fb

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

bit_manipulation/log_two.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
/**
2+
* @author dev-madhurendra <https://github.com/dev-madhurendra>
3+
* @see https://handwiki.org/wiki/Binary_logarithm
4+
* Approximate log2 using bitwise operators
5+
* @param {number} n
6+
* @returns {number} Log2 approximation equal to floor(log2(n))
7+
*/
8+
export const logTwo = (n: number): number => {
9+
let result = 0
10+
while (n >> 1) {
11+
n >>= 1
12+
result++
13+
}
14+
return result
15+
}

bit_manipulation/test/log_two.test.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { logTwo } from "../log_two"
2+
3+
describe('LogTwoTests' , () => {
4+
test.each([...Array(100).keys()].map(i => [i + 1]))(
5+
'log2(%i)',
6+
(input) => {
7+
expect(logTwo(input)).toBe(Math.floor(Math.log2(input)));
8+
}
9+
);
10+
})

0 commit comments

Comments
 (0)