-
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.
use string conversion for countdigits
- Loading branch information
1 parent
9fff0fb
commit 98344e1
Showing
1 changed file
with
3 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,41 +1,12 @@ | ||
package datatypes | ||
|
||
import ( | ||
"math" | ||
"math/big" | ||
) | ||
|
||
var tenInt = big.NewInt(10) | ||
|
||
func CountDigits(bi *big.Int) int { | ||
tenInt := big.NewInt(10) | ||
if bi.IsUint64() { | ||
u64 := bi.Uint64() | ||
if u64 < (1 << 53) { // Check if it is less than 2^53 | ||
if u64 == 0 { | ||
return 1 // 0 has one digit | ||
} | ||
return int(math.Log10(float64(u64))) + 1 | ||
} | ||
} else if bi.IsInt64() { | ||
i64 := bi.Int64() | ||
if i64 > -(1 << 53) { // Check if it is greater than -2^53 | ||
if i64 == 0 { | ||
return 1 // 0 has one digit | ||
} | ||
return int(math.Log10(float64(-i64))) + 1 | ||
} | ||
if bi.Sign() < 0 { | ||
return len(bi.String()) - 1 | ||
} | ||
|
||
// For larger numbers, use the bit length and logarithms | ||
abs := new(big.Int).Abs(bi) | ||
lg10 := int(float64(abs.BitLen()) / math.Log2(10)) | ||
|
||
// Verify and adjust lg10 if necessary | ||
check := new(big.Int).Exp(tenInt, big.NewInt(int64(lg10)), nil) | ||
if abs.Cmp(check) >= 0 { | ||
lg10++ | ||
} | ||
|
||
return lg10 | ||
return len(bi.String()) | ||
} |