10

What is the complexity of converting a very large n-bit number to a decimal representation?

My thought is that the elementary algorithm of repeated integer division, taking the remainder to get each digit, would have O(M(n)log n) complexity, where M(n) is the complexity of the multiplication algorithm; however, the division is not between 2 n-bit numbers but rather 1 n-bit number and a small constant number, so it seems to me the complexity could be smaller.

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Tanner
  • 101
  • 1
  • 3

1 Answers1

4

Naive base-conversion as you described takes quadratic time; you do about n bigint-by-smallint divisions, most of which take time linear in the size of the n-bit bigint.

You can do base conversion in O(M(n) log(n)) time, however, by picking a power of target-base that's roughly the square root of the to-be-converted number, doing divide-and-remainder by it (which can be done in O(M(n)) time via Newton's method), and recursing on the two halves.

tmyklebu
  • 13,915
  • 3
  • 28
  • 57
  • I guess my question is whether or not division by a small number can be done in linear time O(n) or less. For example, division by 2 or 4 is trivially O(1); is there an O(n) algorithm for division by 10? – Tanner Feb 09 '15 at 20:37
  • how is division by 2 O(1)? youll have to shift all bits, no? – G. Bach Feb 09 '15 at 20:53
  • @Tanner, yes, division by any fixed divisor is O(n), where n is the length of the dividend. Just use the usual long division algorithm. Allowing arbitrary divisors changes things. – dfeuer Feb 09 '15 at 20:53
  • @G.Bach, I think the idea there is that if you're representing the number as a little-endian list of bits, you can divide by 2 using `drop 1`. – dfeuer Feb 09 '15 at 20:54
  • @xdavidliu: I don't follow. Do you have an algorithm for computing the product of two n-bit numbers that does not need to examine at least a constant fraction of the bits of the input, or write at least a constant fraction of the bits of the output? – tmyklebu Dec 23 '17 at 14:57
  • @tmyklebu (I just deleted my comment, which was not correct) I incorrectly assumed that all divisions, even ones at deeper recursive levels, act on a single word of the top-level n, so take M(n) time, even for inputs of size n/2, n/4, etc. In fact, the divisions are deeper levels act on smaller input sizes, which was not clear to me. – xdavidliu Dec 23 '17 at 15:19
  • Anyone have a link to a paper or implementation of this `O( M(n) log(n) )` algorithm? – Meekohi Jul 08 '21 at 17:35
  • 1
    @Meekohi try [this link](http://maths-people.anu.edu.au/~brent/pd/rpb032.pdf), page 14 – Lev Knoblock Sep 14 '21 at 22:15