1

I'm trying to use BigInteger values along side Math.Log10 method.

final BigInteger answerNo = fact;
final int digits = 1 + (int)Math.floor(Math.log10(answerNo));

Unfortunately the compiler says incompatible types.

If I change the ints to BigIntegers it still doesn't like it.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
binary101
  • 1,013
  • 3
  • 23
  • 34
  • I've changed the title of this question to make it comply with the information in the question and accepted answer. Obviously counting the digits is not as precise as performing an actual 10 based logarithm. – Maarten Bodewes Sep 26 '15 at 14:19

3 Answers3

7

Instead of doing a log10 you can find the number of digits by simply doing:

int digits = answerNo.toString().length();
epsalon
  • 2,294
  • 12
  • 19
1
  1. You can't assign an int to a BigInteger - you could write: final BigInteger answerNo = BigInteger.valueOf(fact);
  2. Mat.log10 expects a double, not a BigInteger

If you don't mind a loss of precision, you could simply use doubles:

final int digits = 1 + (int)Math.floor(Math.log10(fact));

If you care about precision, you will need to calculate the log manually.

assylias
  • 321,522
  • 82
  • 660
  • 783
0

BigInteger.toString() can be inefficient in terms of memory if you only care for count of digits.

You can instead try converting BigInteger into a BigDecimal and use the BigDecimal.precision() to achieve the same. See this answer for details.

ajay
  • 31
  • 5