Created
December 7, 2024 20:05
-
-
Save Mr-Bossman/dddb7fc49daa27e8e50299e330912efe to your computer and use it in GitHub Desktop.
A generalized divisibility rule for binary inspired by Matt at Stand-up Maths https://www.youtube.com/watch?v=6pLz8wEQYkA
This file contains hidden or 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 <stdio.h> | |
#include <stdbool.h> | |
#include <stdint.h> | |
bool is_divisible(uint64_t n, uint64_t divisor) { | |
while((divisor % 2) == 0) { | |
if((n % 2)) | |
return false; | |
n /= 2; | |
divisor /= 2; | |
} | |
while((n % 2) == 0) | |
n /= 2; | |
while(n > divisor) { | |
n -= divisor; | |
while((n % 2) == 0) | |
n /= 2; | |
} | |
return n == divisor; | |
} | |
int main() { | |
for (uint64_t n = 2; n < 17; n++) { | |
for (uint64_t i = 2; i <= n; i++) { | |
if (is_divisible(n, i)) { | |
printf("%lu %% %lu == 0\n", n, i); | |
} | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment