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 | 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 | 167 |
2 | Um_nik | 163 |
3 | maomao90 | 162 |
3 | atcoder_official | 162 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 157 |
8 | TheScrasse | 154 |
9 | Dominater069 | 153 |
9 | nor | 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$$$