8

I need to find the number of digits of very large multiplications (about 300 digits each). I was wondering if there is a trick to predict the number of digits that the product will be without actually performing the calculation.

Descartes
  • 503
  • 2
  • 7
  • 22

2 Answers2

23

The number of digits can be calculated exactly by the rounded (down) sum of the base 10 log of the two multiplicands plus 1, as follows:

public static void main(String[] args) {
    DecimalFormat f = new DecimalFormat("#");
    double num1 = 12345678901234567890d;
    double num2 = 314159265358979d;

    // Here's the line that does the work:
    int numberOfDigits = (int) (Math.log10(num1) + Math.log10(num2)) + 1;

    System.out.println(f.format(num1) + " * " + f.format(num2) + " = " + 
        f.format((num1 * num2)) + ", which has " + numberOfDigits + " digits");
}

Output:

12345678901234567000 * 314159265358979 = 3878509413969699000000000000000000, which has 34 digits

This will work for arbitrarily large numbers.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
7

Cristobalito's answer pretty much gets it. Let me make the "about" more precise:

Suppose the first number has n digits, and the second has m. The lowest they could be is 10^(n-1) and 10^(m-1) respectively. That product would the lowest it could be, and would be 10^(m+n-2), which is m+n-1 digits.

The highest they could be is 10^n - 1 and 10^m - 1 respectively. That product would be the highest it could be, and would be 10^(n+m) - 10^n - 10^m + 1, which has at most m+n digits.

Thus if you are multiplying an n-digit number by an m-digit number, the product will have either m+n-1 or m+n digits.

Similar logic holds for other bases, such as base 2.

Domingo Ignacio
  • 1,194
  • 7
  • 13
  • The base 10 logarithm, which other posters describe, is a simple technique. However, you could just find the base 2 logarithm and multiply by (log 2)/(log 10), which is about 0.693. The base 2 logarithm can be found without resorting to floating point by just finding the position of the most significant 1 in the binary representation. If you then multiply by 69 and integer divide by 100, you should find the approximate digit count without ever using anything but integer operations. You probably shouldn't ever do this, as it'd probably never actually be worth the trouble. Cute, though, no? – Domingo Ignacio Jul 03 '11 at 23:44
  • Why not add your comment here to the answer? – Paŭlo Ebermann Jul 04 '11 at 00:24
  • 1
    Because I believe it's unlikely to be genuinely useful in practice. – Domingo Ignacio Jul 04 '11 at 00:26
  • I think this answer does not make sense given Bohemians answer because you can compute it exactly, e,g, "Thus if you are multiplying an n-digit number by an m-digit number, the product will have either m+n-1 or m+n digits." is a loose bound but you can do better. – Tommy Mar 01 '16 at 21:23