Files
2026-05-20 20:33:10 +02:00

91 lines
1.3 KiB
C

#ifndef UC_MATH_H_
#define UC_MATH_H_
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
uint32_t
uc_gcd_32(uint32_t a, uint32_t b);
uint64_t
uc_gcd_64(uint64_t a, uint64_t b);
uint32_t
uc_phi_32(uint32_t N);
uint64_t
uc_phi_64(uint64_t N);
#if defined(__has_builtin)
# if __has_builtin(__builtin_clzll)
# define HAVE_BUILTIN_CLZ 1
# endif
#endif
// Note: the nextpow2 functions have undefined behavior if
// x > 2^(n-1) for n of the 32 or 64 bit variants
#if HAVE_BUILTIN_CLZ
static inline uint32_t
uc_nextpow2(uint32_t x)
{
if (x <= 1) return 1;
return 1u << (32 - __builtin_clz(x - 1));
return x;
}
static inline uint64_t
uc_nextpow2_64(uint64_t x)
{
if (x <= 1) return 1;
return (uint64_t)1 << (64 - __builtin_clzll(x - 1));
return x;
}
#else
static inline uint32_t
uc_nextpow2(uint32_t x)
{
if (x == 0) {
return 1;
}
x--;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
x++;
return x;
}
static inline uint64_t
uc_nextpow2_64(uint64_t x)
{
if (x == 0) {
return 1;
}
x--;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
x |= x >> 32;
x++;
return x;
}
#endif
#undef HAVE_BUILTIN_CLZ
#ifdef __cplusplus
}
#endif
#endif