Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Module of Power of Two Using Bitmask #1355

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Bit-Manipulation/ModuleOfPowerOfTwo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* @author: gianvallejos92
* This script will find the module of S % N using bitmask
* N is power of 2. E.g: 1, 2, 4, 8, 16, 32...
* Reference: https://www.geeksforgeeks.org/compute-modulus-division-by-a-power-of-2-number/
*/

export const ModuleOfPowerOfTwo = (s, n) => {
return (s & (n - 1))
}
36 changes: 36 additions & 0 deletions Bit-Manipulation/test/ModuleOfPowerOfTwo.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { ModuleOfPowerOfTwo } from '../ModuleOfPowerOfTwo'

test('Check 7 module 4', () => {
const res = ModuleOfPowerOfTwo(7, 4)
expect(res).toBe(3)
})

test('Check 150 module 4', () => {
const res = ModuleOfPowerOfTwo(150, 4)
expect(res).toBe(2)
})

test('Check 155 module 2', () => {
const res = ModuleOfPowerOfTwo(155, 2)
expect(res).toBe(1)
})

test('Check 150 module 16', () => {
const res = ModuleOfPowerOfTwo(150, 16)
expect(res).toBe(6)
})

test('Check 6 module 4', () => {
const res = ModuleOfPowerOfTwo(6, 4)
expect(res).toBe(2)
})

test('Check 12 module 8', () => {
const res = ModuleOfPowerOfTwo(12, 8)
expect(res).toBe(4)
})

test('Check 10 module 2', () => {
const res = ModuleOfPowerOfTwo(10, 2)
expect(res).toBe(0)
})