Created
July 10, 2020 18:31
-
-
Save cortezcristian/020f1f2d3e5d3b7ea348a99c89b43614 to your computer and use it in GitHub Desktop.
Coding the Josephus Problem solution2.js
This file contains 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
let nearestLowerPow2 = function (x) { | |
if (x == 0) return 0; | |
const arr = [1, 2, 4, 8, 16]; | |
arr.forEach(function(n) { | |
x |= (x >> n); | |
}); | |
return x - (x >> 1); | |
} | |
// Second solution based on the formula | |
const solution2 = (n) => { | |
let lowPow2 = nearestLowerPow2(n); | |
return 2*(n-lowPow2)+1; | |
}; | |
const position = solution2(5); | |
console.log(position); // >>> 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment