Skip to content

Instantly share code, notes, and snippets.

@cortezcristian
Created July 10, 2020 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cortezcristian/020f1f2d3e5d3b7ea348a99c89b43614 to your computer and use it in GitHub Desktop.
Save cortezcristian/020f1f2d3e5d3b7ea348a99c89b43614 to your computer and use it in GitHub Desktop.
Coding the Josephus Problem solution2.js
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