Created
December 10, 2024 18:15
-
-
Save lemire/7847922ac3436ad801847b638937f761 to your computer and use it in GitHub Desktop.
five functions in C that could be faster
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 <stdint.h> | |
#include <stdlib.h> | |
#include <stdbool.h> | |
int count(uint64_t x) { | |
int count = 0; | |
for(int k = 0; k < 64; k++) { | |
count += (x&1); | |
x >>= 1; | |
} | |
return count; | |
} | |
uint64_t prefix(uint64_t * x, int length) { | |
if(length == 0) { return 0; } | |
uint64_t * array = ( uint64_t *)malloc(length * sizeof(uint64_t)); | |
array[0] = x[0]; | |
for(int k = 1; k < length; k++) { | |
array[k] = x[k] + array[k-1]; | |
} | |
uint64_t answer = array[length-1]; | |
free(array); | |
return answer; | |
} | |
bool match(const char * x) { | |
bool answer = false; | |
for(int k = 0; k < 1000; k++) { | |
if(x[k] == 'c' || x[k] == 'z' || x[k] == '"' || x[k] == '*' || x[k] == '&') { | |
answer = true; | |
} | |
} | |
return answer; | |
} | |
bool digit(const char * x) { | |
bool answer = true; | |
for(int k = 0; k < 8; k++) { | |
answer &= (x[k] >= '0' && x[k] <= '9'); | |
} | |
return answer; | |
} | |
uint64_t unique(uint64_t * x, int length) { | |
bool uni = true; | |
for(int k = 0; k < length; k++) { | |
uint64_t current = x[k]; | |
int count = 0; | |
for(int l = 0; l < length; l++) { | |
if(x[l] == current) { count ++;} | |
} | |
if(count != 1) { uni = false; } | |
} | |
return uni; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment