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 | 3993 |
2 | jiangly | 3743 |
3 | orzdevinwang | 3707 |
4 | Radewoosh | 3627 |
5 | jqdai0815 | 3620 |
6 | Benq | 3564 |
7 | Kevin114514 | 3443 |
8 | ksun48 | 3434 |
9 | Rewinding | 3397 |
10 | Um_nik | 3396 |
# | User | Contrib. |
---|---|---|
1 | cry | 167 |
2 | Um_nik | 163 |
3 | maomao90 | 162 |
3 | atcoder_official | 162 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 155 |
8 | TheScrasse | 154 |
9 | Dominater069 | 153 |
10 | djm03178 | 152 |
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)
):