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 | tourist | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 161 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | awoo | 154 |
8 | Dominater069 | 154 |
10 | luogu_official | 150 |
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)
):