查找大BigInteger的日志不能正常工作

本文关键字:常工作 工作 不能 BigInteger 日志 查找 | 更新日期: 2023-09-27 18:15:26

我试图找到c#中一个非常大的BigInteger的对数。我不关心对数的底数是多少。当我尝试这个:

BigInteger b = 1000; // the base
// myBigInt is a huge BigInt i want to find the Log of.
exponent = BigInteger.Log(myBigInt, 1000); //Find the Log
// Re-create the orignal BigInt now that I know base and exponent
BigInteger.Pow(b, Convert.ToInt32(exponent)); 

我得到一个溢出异常,因为Int32不能保存日志的结果。

查找大BigInteger的日志不能正常工作

您在日志和pow中使用的基础不相同

BigInteger bigInt = 10000000000000000000;  // myBigInt is a huge BigInt i want to find the Log of.
double log;
log = BigInteger.Log(bigInt, 1000); //Find the Log
System.Diagnostics.Debug.WriteLine(log.ToString());
System.Diagnostics.Debug.WriteLine(((Int32)log).ToString());
BigInteger bigIntRecreate;
// unless log is an integer value it will round down and will not recreate to proper value
bigIntRecreate = BigInteger.Pow(1000, (Int32)log);
System.Diagnostics.Debug.WriteLine(bigInt.ToString("N0"));
System.Diagnostics.Debug.WriteLine(bigIntRecreate.ToString("N0"));
System.Diagnostics.Debug.WriteLine((bigInt - bigIntRecreate).ToString("N0"));