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

Add/highest power of 2 #195

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

vcnovaes
Copy link
Contributor

Find the highest power of two smaller or equal a given number n

@vcnovaes
Copy link
Contributor Author

Please, merge it under hacktoberfest

1 similar comment
@vcnovaes
Copy link
Contributor Author

Please, merge it under hacktoberfest

Copy link
Contributor

@appgurueu appgurueu left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems at least partially redundant with #193:

  • Given this, can't I implement nextPowerOf2(n) as highestPowerOf2(n) << 1, with the exception of n == highestPowerOf2(n) being handled specially (not shifting in that case)?
  • This also goes the other way, so highestPowerOf2 could be implemented in terms of nextPowerOf2 as well.

The more general "bit twiddling" primitive between both of these is count leading zeros (clz). What if you just implemented that instead?


export const highestPowerOf2 = (n: number) => {
let result = 0;
for (let i = n; i >= 1; i--) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This loop seems somewhat sketchy, given that it only reduces n by one in each iteration. Linear runtime in n is not acceptable, this should be logarithmic in n (and thus linear in the number of bits).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants