FastLED 3.10.6
Loading...
Searching...
No Matches
icbrt.h
Go to the documentation of this file.
1#pragma once
2
3// Integer cube root for fixed-point types.
4// Bit-by-bit algorithm — no float, no division, no multiplication by a
5// non-constant. Companion to isqrt.h; see that file for why the algorithm
6// is expressed as tail recursion (C++11 constexpr forbids loops) and why
7// FL_OPTIMIZE_FUNCTION is required to keep low optimization levels from
8// emitting a stack frame per iteration.
9//
10// The recurrence carries the running root `y` and its square `y2` so that
11// each step needs only shifts and adds:
12//
13// y <- 2y y2 <- 4y2
14// B = 3(y2 + y) + 1
15// if (x >> s) >= B then x -= B << s, y += 1, y2 += 2y + 1
16//
17// The comparison is written `(x >> s) >= B` rather than `x >= (B << s)`
18// because `B << s` overflows u64 on the first steps of a large input, while
19// the shifted-right form is exact for integers and never does. `B << s` is
20// then only evaluated on the branch where it is known to be <= x.
21//
22// 22 steps (s = 63, 60, ... 0) cover the whole u64 domain; the result of
23// icbrt64 is therefore always below 2^22.
24
25#include "fl/stl/compiler_control.h" // FL_OPTIMIZE_FUNCTION
26#include "fl/stl/int.h"
27#include "fl/stl/noexcept.h"
28
30
31namespace fl {
32
33FL_OPTIMIZE_FUNCTION constexpr inline u32 _icbrt64_step(u64 x, u64 y, u64 y2, int s) FL_NO_EXCEPT {
34 return s < 0
35 ? static_cast<u32>(y)
36 : ((x >> s) >= 3 * ((y2 << 2) + (y << 1)) + 1)
37 ? _icbrt64_step(x - ((3 * ((y2 << 2) + (y << 1)) + 1) << s),
38 (y << 1) + 1,
39 (y2 << 2) + (y << 2) + 1,
40 s - 3)
41 : _icbrt64_step(x, y << 1, y2 << 2, s - 3);
42}
43
44// Largest u32 whose cube does not exceed x.
46 return _icbrt64_step(x, 0, 0, 63);
47}
48
49} // namespace fl
50
#define FL_OPTIMIZATION_LEVEL_O3_BEGIN
#define FL_OPTIMIZATION_LEVEL_O3_END
#define FL_OPTIMIZE_FUNCTION
FL_OPTIMIZE_FUNCTION constexpr u32 icbrt64(u64 x) FL_NO_EXCEPT
Definition icbrt.h:45
FL_OPTIMIZE_FUNCTION constexpr u32 _icbrt64_step(u64 x, u64 y, u64 y2, int s) FL_NO_EXCEPT
Definition icbrt.h:33
InputGamut g FL_NO_EXCEPT
Definition rgbw.h:121
Base definition for an LED controller.
Definition crgb.hpp:179
fl::u64 u64
Definition stdint.h:220