Fastest way to convert a BigInteger to a decimal (Base 10) string?

前端 未结 2 567
心在旅途
心在旅途 2020-12-21 10:13

Answers So Far

So here is the code breakdown.

//Time: ~7s (linear loop algorithm)
//100,000! (456,574 decimal digits)
BigInteger bigIntVar = comput         


        
2条回答
  •  执笔经年
    2020-12-21 10:49

    First I'd calculate all numbers of the form 10^(2^m) smaller than n. Then I'd use DivRem with the largest of these to split the problem into two subproblems. Repeat that recursively until you're down to individual digits.

    var powersOfTen=new List();
    powersOfTen.Add(1);
    for(BigInteger i=10;i

    You can also optimize out the string concatenation entirely by directly writing into a character array.


    Alternatively you could consider using base 1000'000'000 during all the calculations. That way you don't need the base conversion in the end at all. That's probably much faster for factorial calculation.

    List multiply(List f1, int f2)
    {
      int carry=0;
      for(int i=0;i

    Now conversion to a base 10 string is trivial and cheap.

提交回复
热议问题