is there any formula to calculate this in O(1)
?
int N;
cin >> N;
int answer = 0;
while (N > 1) {
N = sqrt(N);
answer++;
}
cout << answer;
# | User | Rating |
---|---|---|
1 | jiangly | 3976 |
2 | tourist | 3815 |
3 | jqdai0815 | 3682 |
4 | ksun48 | 3614 |
5 | orzdevinwang | 3526 |
6 | ecnerwala | 3514 |
7 | Benq | 3482 |
8 | hos.lyric | 3382 |
9 | gamegame | 3374 |
10 | heuristica | 3357 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | -is-this-fft- | 165 |
3 | atcoder_official | 160 |
3 | Um_nik | 160 |
5 | djm03178 | 157 |
6 | Dominater069 | 156 |
7 | adamant | 153 |
8 | luogu_official | 152 |
9 | awoo | 151 |
10 | TheScrasse | 147 |
is there any formula to calculate this in O(1)
?
int N;
cin >> N;
int answer = 0;
while (N > 1) {
N = sqrt(N);
answer++;
}
cout << answer;
Name |
---|
This one works in O( log(log(n)) )
can you explain this ?
Imagine bit representation of n, let it be n = 16 (in bits 10000), sqrt of 16 is 4 (in bits 100), if n = 25 (11001 in bits) sqrt is 5 (in bits 101), size of bit representation after sqrt is always (bit representation size + 1)/2, we need to make size equal of 1 so number of operations is log(bit representation size of n) because after every sqrt it becomes half of initial size, it's little hard for me to explain, sorry.
Instead of powerOfTwo(n) + 1 you can just write (31 — __builtin_clz(i)), result is the same I guess.
Yeah it's absolutely right.
We can see that result for $$${2 ^ {2 ^ n}}$$$ is $$$n + 1$$$. Result for $$${2 ^ {2 ^ n}} \leqslant k \leqslant {2 ^ {2 ^ n + 1}}$$$ is $$$n + 1$$$. So the formula for $$$n$$$ is $$$\log(\log(n)) + 1$$$. In C++ such function as
__builtin_clz
has O(1) complexity.Code (code works properly for int type, for 64-bit integers use
63 - __builtin_clzll(x)
):