Author:水如烟
大数的表示形式必然是字符串。
大数的运算,无论是加法或乘法,必须能够分拆运算,基于:
运算过程中,由于内存或存储介质限制;
需要多线程运算;
需要分布式运算。
为了充分利用计算机内部的运算能力,充分利用程序平台提供的存储和运算能力,运算单元要高效运算。
如果是分布式运算,要求所有客户端程序平台要统一。这里要求.NET Frmework版本统一。(这点有点不妥,可以考虑解决)
Public Class Information
Private Sub New()
End Sub
Private Shared gUnitMaxSize As Integer
Private Shared gUnitDataType As TypeCode
''' <summary>
''' 运算单元最大位数
''' </summary>
Public Shared ReadOnly Property UnitMaxSize() As Integer
Get
Return gUnitMaxSize
End Get
End Property
''' <summary>
''' 运算单元数据类型
''' </summary>
''' <value></value>
Public Shared ReadOnly Property UnitDataType() As TypeCode
Get
Return gUnitDataType
End Get
End Property
''' <summary>
''' 转换为运算单元数据类型
''' </summary>
''' <param name="Value">值</param>
Public Shared Function ConverToUnitDataType(ByVal Value As Object) As Object
Return System.Convert.ChangeType(Value, gUnitDataType)
End Function
Shared Sub New()
'寻找可表示为整数的且表示范围最大的数据类型
Dim mTypeName As String
Dim mType As Type
Dim mFieldInfo As Reflection.FieldInfo
Dim mMaxValue As String = "0"
Dim mDataTypeCode As TypeCode
Dim mCurrentTypeMaxValue As String = "0"
For Each c As TypeCode In [Enum].GetValues(GetType(TypeCode))
mTypeName = c.ToString
mType = Type.GetType(String.Format("System.{0}", mTypeName))
mFieldInfo = mType.GetField("MaxValue")
If mFieldInfo Is Nothing Then Continue For
mCurrentTypeMaxValue = mFieldInfo.GetValue(Nothing).ToString
If IsNumeric(mCurrentTypeMaxValue) Then
If mCurrentTypeMaxValue.Length > mMaxValue.Length Then
mMaxValue = mCurrentTypeMaxValue
mDataTypeCode = c
End If
End If
Next
gUnitDataType = mDataTypeCode
'确定该数据类型下,可表示的最大位数。保证两数相乘结果仍可表示为整数。
Dim x As Object
x = ConverToUnitDataType(mMaxValue)
Dim mSqrtResult As String = Math.Sqrt(CDbl(x)).ToString '最大数开方
Dim mPointIndex As Integer = mSqrtResult.IndexOf("."c) '只取整数部分
If mPointIndex > 0 Then
mSqrtResult = mSqrtResult.Substring(0, mPointIndex)
End If
Dim mDigits As Integer = mSqrtResult.ToString.Length - 1 '可表示的最大位数是最大数开方后整数部分位数减一位
gUnitMaxSize = mDigits
End Sub
Friend Const MSG_UNIT_SIZE_OVERFLOW As String = "字串大于{0}位"
Friend Const MSG_UNIT_CARRY_OVERFLOW As String = "上次运算已有进位,不能再次运算"
End Class
加、乘法原理示意:
已知:
A=a1a2a3…an-1an
B=b1b2b3…bm-1bm
加法:
A+B= a1a2a3…(an-m+1+b1)…(an-m+i+bi)…(an-1+ bm-1)(an+ bm)
乘法,分解图:
A*B = a1a2a3…an-1an * b1b2b3…bm-1bm
=∑a1a2a3…an-1an * bi
=∑ai * bj
A=A1A2A3…An-1An
B=B1B2B3…Bm-1Bm
A+B=∑An-m+i+Bi
A*B=∑Ai * Bj
呵,不知能不能实现。一步步,一个个单元想想做做看看。