开发者

How to use the equivalent of indexof() with biginteger in VB.Net?

I am trying to sum up the digits in a very large number. I have gotten the length of the number with

l = answer.bitLength() but I can't figure out how to increament through each digit using a For loop. Any ideas?

I'm using the java.math.biginteger.

Visual Studio 2005 Version 2.0

I should also add that I can't seem to use <> or any of the simple math options with the biginteger I'm using. If anyone could tell me how to use a different biginteger I would be more than willing to swap.

Dim answer As java.math.BigInteger
Dim sum As Integer = 0
Dim x As Integer
Dim i As Integer
'Sets value of answer equal to 1
answer = java.math.BigInteger开发者_Go百科.valueOf(1)

'gets 100!
For i = 1 To 100
answer = answer.multiply(java.math.BigInteger.valueOf(i))
Next

'gets length of answer
Dim l As Integer
l = answer.bitLength()

'Sums up digits in 100!
For x = 0 To l - 1
'Need to pull each character here to add them all up
Next

Final Solution for summing up the digits. Thanks to wageoghe.

Dim r As Integer
Dim s As Integer
s = 0
While (answer.compareTo(java.math.BigInteger.valueOf(0)) > 0)

r = answer.mod(java.math.BigInteger.valueOf(10)).ToString()
s = s + r
answer = answer.divide(java.math.BigInteger.valueOf(10))

End While


Something like this should work:

    Dim bi As New System.Numerics.BigInteger(12345)
    Dim c As Char
    Dim s As Long

    s = 0

    For Each c In bi.ToString()
        s = s + Integer.Parse(c.ToString())
    Next

Or this more conventional way using Mod and / (integer division)

    Dim bi As New System.Numerics.BigInteger(12345)
    Dim s As Long
    Dim r As Integer

    s = 0

    While bi <> 0
        r = bi Mod 10
        s = s + r
        bi = bi / 10
    End While


If you think of the number as a list of binary characters, then you could get the least significant hex digit by ANDing the number with 0xF. If you then shifted the number right by 4 bits (>> 4), then you could get the next hex digit.

After you get all of the hex digits, you could sum them up and then convert them to decimal.


Another approach, is to do the following (this assumes that answer is positive):

int sum = 0;
while(answer > 0){
    sum += answer % 10;
    answer /= 10;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜