i want to make a function that counts the amount of digits once the value is sumed up
lets say i have this array
byte[] array = new byte[] { 200, 100, 200, 250, 150, 100, 200 };
once this is sumed up you'll have a value of 1200
you can get the amount of digits with these functions
Math.Floor(Math.Log10(1200) 1) // 4
but if i sum it up and there are too many values in the array i get an integer overflow
public decimal countDigits(byte[] array)
{
decimal count = array[0];
for (int i = 1; i < array.Length; i )
{
count = Math.Log10(Math.Pow(count, 10) array[i]);
}
return count;
}
this does give the correct output i want but this causes a integeroverflow if the count is greater than 28.898879583742193 (log10(decimal.MaxValue))
CodePudding user response:
Let's put a simple question: how many byte
s should we sum in order to get integer overflow with long
? The answer is simple: in the worst case (all bytes are of maximum possible value) it requires
long.MaxValue / byte.MaxValue 1 = 36170086419038337 (~3.61e16) bytes
How long are we going to sum? Even if it requires just 1
cpu tick (~ 0.1
ns) to get item from array and sum we require
~3.6e6
seconds which is 41 day (or 82 days in case of ulong
). If it's not your case (note, that array in C# can't have more than 2.1e9
items when we want at least 3.6e16
), then you can just sum as long
(or ulong
):
public static int countNumbers(byte[] array) {
ulong sum = 0;
foreach (byte item in array)
sum = item;
// How many digits do we have?
return sum.ToString().Length;
}
CodePudding user response:
i want to make a function that counts the amount of digits once the value is sumed up
public decimal countNumbers(byte[] array)
{
// sum the values...
decimal sum = 0;
foreach (byte value in array)
{
sum = value
}
// ... then "count" the digits.
return Math.Floor(Math.Log10(sum) 1);
}
This would be the code then, however your Question, the provided example and the naming of your method all imply different things so see if that helps, and if it does, please work on your naming.
CodePudding user response:
There's a BigInteger
data type that can sum up arbitrary (integer) values. It even has a Log10
method, so it works very similar to a standard integer variable. The only limitation is that the result of BigInteger.Log10
must be smaller than Double.MaxValue
, but that sounds like a reasonable limitation. (10^1E308=10^10^308 is a really huge number)