سؤال

I'm trying to find the logarithm of a very large BigInteger in C#. I don't care what the base of the logarithm is. When I try this:

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)); 

I get an overflow exception, because Int32 cannot hold the result of the Log. Increasing the value of base doesn't work.

هل كانت مفيدة؟

المحلول

You are not using the same basis in the log and 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"));
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top