如何在 VB.Net 中使用与 biginteger 等效的 indexof() ?
我正在尝试将一个非常大的数字相加。我已经得到了数字的长度l = answer.bitLength()
但我不知道如何使用 For 循环来增加每个数字。有什么想法吗?
我正在使用java.math.biginteger
。
Visual Studio 2005 Version 2.0
我还应该补充一点,我似乎无法使用 <>或我正在使用的 biginteger 的任何简单数学选项。如果有人能告诉我如何使用不同的大整数,我将非常愿意交换。
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.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
对数字求和的最终解决方案。感谢瓦戈格。
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
I am trying to sum up the digits in a very large number. I have gotten the length of the number withl = 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.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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
像这样的东西应该有效:
或者使用 Mod 和 / (整数除法)这种更传统的方式
Something like this should work:
Or this more conventional way using Mod and / (integer division)
如果您将数字视为二进制字符列表,那么您可以通过将数字与
0xF
进行“与”运算来获得最低有效的十六进制数字。如果您随后将数字右移 4 位 (>> 4
),那么您可以获得下一个十六进制数字。获得所有十六进制数字后,您可以将它们相加,然后 将它们转换为十进制。
If you think of the number as a list of binary characters, then you could get the least significant hex digit by
AND
ing the number with0xF
. 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.
另一种方法是执行以下操作(假设
answer
是肯定的):Another approach, is to do the following (this assumes that
answer
is positive):