Given, two binary number A and B (A > B). Each of A and B can have at most 10^5 digits. You have to calculate (A^2 — B^2). [Here, (A^2) denotes the A power of 2].
What should be the approach to calculate A^2?
# | User | Rating |
---|---|---|
1 | tourist | 4009 |
2 | jiangly | 3831 |
3 | Radewoosh | 3646 |
4 | jqdai0815 | 3620 |
4 | Benq | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | gamegame | 3386 |
10 | ksun48 | 3373 |
# | User | Contrib. |
---|---|---|
1 | cry | 164 |
1 | maomao90 | 164 |
3 | Um_nik | 163 |
4 | atcoder_official | 160 |
5 | -is-this-fft- | 158 |
6 | awoo | 157 |
7 | adamant | 156 |
8 | TheScrasse | 154 |
8 | nor | 154 |
10 | Dominater069 | 153 |
Given, two binary number A and B (A > B). Each of A and B can have at most 10^5 digits. You have to calculate (A^2 — B^2). [Here, (A^2) denotes the A power of 2].
What should be the approach to calculate A^2?
Name |
---|
use strings in c++, may be python. going to take about a minute on modern computer.
You can transform A from base 2 to some 2 ^ k base to make the operations more efficient.
Start from the end and divide the binary string in chunks of k bits each (the last chunk can have less than k bits). For each chunk, calculate the number it represents.
Example: 10100110101, k = 3;
=> (10)(100)(110)(101) = (2)(4)(6)(5) = 2465
And then, you can calculate A ^ 2, using simple arithmetic.
Complexity: O(N ^ 2), with the constant logk(2) ^ 2.
Since $$$N = 10^5$$$, this solution is very slow.
Use FFT to find $$$A^2$$$. Any binary number would be $$$\sum\limits_{i=0}^{N} a_ix^i$$$, where $$$a_i = 0/1$$$ and $$$x = 2$$$. So you need to multiply this polynomial with itself and then find the value at $$$x = 2$$$. You can read more about it here
Complexity : $$$O(N*log(N))$$$, where $$$N = 10^5$$$
i prefer $$$x=1000$$$