-
Notifications
You must be signed in to change notification settings - Fork 97
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
4b3807c
commit b5774c0
Showing
2 changed files
with
24 additions
and
32 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,12 +1,33 @@ | ||
package datatypes | ||
|
||
import ( | ||
"math" | ||
"math/big" | ||
) | ||
|
||
var tenInt = big.NewInt(10) | ||
|
||
func CountDigits(bi *big.Int) int { | ||
if bi.Sign() < 0 { | ||
return len(bi.String()) - 1 | ||
if bi.IsInt64() { | ||
i64 := bi.Int64() | ||
// restrict fast path to integers with exact conversion to float64 | ||
if i64 <= (1<<53) && i64 >= -(1<<53) { | ||
if i64 == 0 { | ||
return 1 | ||
} | ||
return int(math.Log10(math.Abs(float64(i64)))) + 1 | ||
} | ||
} | ||
|
||
estimatedNumDigits := int(float64(bi.BitLen()) / math.Log2(10)) | ||
|
||
// estimatedNumDigits (lg10) may be off by 1, need to verify | ||
digitsBigInt := big.NewInt(int64(estimatedNumDigits)) | ||
errorCorrectionUnit := digitsBigInt.Exp(tenInt, digitsBigInt, nil) | ||
|
||
if bi.CmpAbs(errorCorrectionUnit) >= 0 { | ||
return estimatedNumDigits + 1 | ||
} | ||
return len(bi.String()) | ||
|
||
return estimatedNumDigits | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters