Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Predicting the number of digits of a multiplication

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.

like image 361
Descartes Avatar asked Jul 03 '11 23:07

Descartes


People also ask

How do you calculate the number of digits?

So it can be concluded that to count number of digits, how many times a number is divided by 10 to reach 1 needs to be calculated. log base 10 of a number is the number of times a number needs to be divided by 10 to reach 1 but as 1 itself is not included in log base 10, 1 is added to get the number of digits.

What is the product of all digits from 0 to 9?

Now, we don't need to calculate the product of ( 1 × 2 × 3 × 4 × 5 × 6 × 7 × 8 × 9) , because the produced answer will be eventually multiplied with zero to produce zero as the obvious final answer. That's why, we can directly write zero as the final answer, without doing any manual calculations.


1 Answers

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.

like image 140
Bohemian Avatar answered Oct 13 '22 00:10

Bohemian