Tuhin_RU's blog

By Tuhin_RU, history, 3 years ago, In English

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?

  • Vote: I like it
  • +3
  • Vote: I do not like it

»
3 years ago, # |
  Vote: I like it 0 Vote: I do not like it

use strings in c++, may be python. going to take about a minute on modern computer.

»
3 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

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.

  • »
    »
    3 years ago, # ^ |
      Vote: I like it +16 Vote: I do not like it

    Since $$$N = 10^5$$$, this solution is very slow.

»
3 years ago, # |
  Vote: I like it +19 Vote: I do not like it

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$$$