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 | 4009 |
2 | jiangly | 3823 |
3 | Benq | 3738 |
4 | Radewoosh | 3633 |
5 | jqdai0815 | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | ksun48 | 3390 |
10 | gamegame | 3386 |
# | User | Contrib. |
---|---|---|
1 | cry | 166 |
2 | maomao90 | 163 |
2 | Um_nik | 163 |
4 | atcoder_official | 161 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 157 |
8 | TheScrasse | 154 |
9 | nor | 153 |
9 | Dominater069 | 153 |
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)
):