Created
November 20, 2023 17:47
-
-
Save colematt/7ce57add13b11364465218d4788e7109 to your computer and use it in GitHub Desktop.
[Generate the next number with a given number of set bits] #c
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
#include <stdint.h> // uint64_t | |
#include <stdio.h> // printf | |
uint64_t twiddle(uint64_t x) { | |
uint64_t smallest, ripple, new_smallest, ones; | |
if (x == 0) | |
return 0; | |
smallest = (x & -x); | |
ripple = x + smallest; | |
new_smallest = (ripple & -ripple); | |
ones = ((new_smallest / smallest) >> 1) - 1; | |
return ripple | ones; | |
} | |
int main() { | |
uint64_t bits = 4; | |
uint64_t a = 0xF; // a = 0b0000....1111 | |
for (int i = 0; i < 100; i++) { | |
printf("Next number is %lu\n", (a = twiddle(a))); | |
} | |
#if 0 | |
while (a <= 0xF000000000000000) { // a = 0b11110000...0000 | |
printf("Next number is %lu\n", (a=twiddle(a))); | |
} | |
#endif | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From Hacker's Delight