I'd go for a non standard function, because C sucks with bit operations:
#include <stdio.h>
#ifdef __GNUC__
int popcount(int x) {
return __builtin_popcount(x);
}
#else
#error Unimplemented popcount
#endif
int main(void)
{
int x;
scanf("%d", &x);
printf("%d\n", popcount(x));
return 0;
}
This will be translated to efficient processor instructions where available, or an efficient library implementation where it's not.
References: http://en.wikipedia.org/wiki/Hamming_weight
http://stackoverflow.com/questions/15736602/fastest-way-to-count-number-of-1s-in-a-register-arm-assembly https://stackoverflow.com/questions/15736602/fastest-way-to-count-number-of-1s-in-a-register-arm-assembly
http://wm.ite.pl/articles/sse-popcount.html
http://gcc.gnu.org/onlinedocs/gcc-4.8.2/gcc/Other-Builtins.html#Other-Builtins
I'd go for a non standard function, because C sucks with bit operations:
#include <stdio.h>
#ifdef __GNUC__
int popcount(int x) {
return __builtin_popcount(x);
}
#else
#error Unimplemented popcount
#endif
int main(void)
{
int x;
scanf("%d", &x);
printf("%d\n", popcount(x));
return 0;
}
This will be translated to efficient processor instructions where available, or an efficient library implementation where it's not.
References: http://en.wikipedia.org/wiki/Hamming_weight
http://wm.ite.pl/articles/sse-popcount.html
http://gcc.gnu.org/onlinedocs/gcc-4.8.2/gcc/Other-Builtins.html#Other-Builtins
I'd go for a non standard function, because C sucks with bit operations:
#include <stdio.h>
#ifdef __GNUC__
int popcount(int x) {
return __builtin_popcount(x);
}
#else
#error Unimplemented popcount
#endif
int main(void)
{
int x;
scanf("%d", &x);
printf("%d\n", popcount(x));
return 0;
}
This will be translated to efficient processor instructions where available, or an efficient library implementation where it's not.
References: http://en.wikipedia.org/wiki/Hamming_weight
http://wm.ite.pl/articles/sse-popcount.html
http://gcc.gnu.org/onlinedocs/gcc-4.8.2/gcc/Other-Builtins.html#Other-Builtins
I'd go for a non standard function, because C sucks with bit operations:
#include <stdio.h>
#ifdef __GNUC__
int popcount(int x) {
return __builtin_popcount(x);
}
#else
#error Unimplemented popcount
#endif
int main(void)
{
int x;
scanf("%d", &x);
printf("%d\n", popcount(x));
return 0;
}
This will be translated to efficient processor instructions where available, or an efficient library implementation where it's not.
References: http://en.wikipedia.org/wiki/Hamming_weight
http://wm.ite.pl/articles/sse-popcount.html
http://gcc.gnu.org/onlinedocs/gcc-4.8.2/gcc/Other-Builtins.html#Other-Builtins