How do I determine the size of a dynamic array?
I'm trying to find the sum of all the digits that make up the number 2^1000, which you may have guessed is from Project Eula. I think it's good so far except I'm just learning about arrays and dynamic arrays, so how will I know what the size of the index will be so I can specify when the Do loop should stop so I don't get an indexoutofrange exception?
vb.net Code:
Dim BigNumber As Double = 2 ^ 1000
Dim DigitArray() As Char = BigNumber.ToString.ToCharArray
Dim Index As Integer = 0
Dim SumOfDigits As Integer = 0
Do Until index
SumOfDigits += Integer.Parse(DigitArray(Index))
Index += 1
Loop
TextBox1.Text = SumOfDigits.ToString
Re: How do I determine the size of a dynamic array?
Something you maybe have missed in your course then... For Each.
And the answer to your actual question is here.
Re: How do I determine the size of a dynamic array?
DigitArray.Length - will return the length of array (mind the fact that all arrays are zero based, so the last element's index in it will be .Length - 1).
Re: How do I determine the size of a dynamic array?
Note that your code will never work. While the Double has enough capacity to store the number 2^1000, it is not precise enough to store the exact amount. It can only tell you it is something like 1.071508 x 10^301. This means the number it stores is actually 1071508000000000000 (lots of 0's) 00000, which is not exactly 2^1000. Your code will tell you the sum of the digits is something in the order or 50 I guess, (assuming you handle the exception when your loop reaches the 'E' which it cannot parse into an integer) because you will simply be adding 0 + 0 + 0 + 0 + 0...
There is no numeric integral type in .NET that can precisely store 2^1000. Maybe the BigInteger structure however will work for this goal (but it might be really slow). The BigInteger should theoretically be able to handle numbers of any size.
EDT
I just read that the ToString of the BigInteger does basically the same thing; it only shows the first 50 digits and replaces the rest with zeroes. To overcome this issue you need to specify the 'R' formatting in the ToString method. Read the comments on the bottom of the documentation here:
http://msdn.microsoft.com/en-us/libr...iginteger.aspx
and especially the documentation of the ToString method:
http://msdn.microsoft.com/en-us/library/dd268260.aspx