數學乘法 從小學開始就一直是基於加法的,所以,我寫了一個基於加法的大數乘法。擴展方法省去了類型轉換的損耗,
原理如下:
1 2 3
* 5 6
------------------------
7 3 8
+ 6 1 5 0 這裏加個0
-------------------------
= 6 8 8 8
好,直接上代碼
using System.Text;
namespace LongNumber
{
public static class LongNumberHelper
{
/// <summary>
/// 大數相乘
/// </summary>
/// <param name="s1"></param>
/// <param name="s2"></param>
/// <returns></returns>
public static string LongNumberMul(string s1, string s2)
{
string result = "";
for (int i = s2.Length - 1; i >= 0; i--)
{
var s = StrMulChar(s1, s2[i], s2.Length - 1 - i);//計算s2每個數的乘積並給結果加足夠的0
result = LongNumberAdd(result, s);//結果集累加
}
return result;
}
/// <summary>
/// 分步計算並進位
/// </summary>
/// <param name="s1"></param>
/// <param name="s2"></param>
/// <param name="count"></param>
/// <returns></returns>
private static string StrMulChar(string s1, char s2, int count)
{
StringBuilder sb = new StringBuilder();
int temp = 0;
for (int i = s1.Length - 1; i >= 0; i--)
{
var s = s1[i].CharToInt() * s2.CharToInt() + temp;
temp = 0;
while (s >= 10)
{
temp++;
s -= 10;
}
sb.Insert(0, s);
}
if (temp > 0)
{
sb.Insert(0, temp);
}
sb.Append('0', count);//給結果加0
return sb.ToString();
}
/// <summary>
/// 極大數加法
/// </summary>
/// <param name="s1"></param>
/// <param name="s2"></param>
/// <returns></returns>
public static string LongNumberAdd(string s1, string s2)
{
string result = "";
if (s1.Length > s2.Length)
{
result = AddToResult(s1, s2);
}
else
{
result = AddToResult(s2, s1);
}
return result;
}
/// <summary>
/// 長的加短的
/// </summary>
/// <param name="s1">長的數</param>
/// <param name="s2">短的數</param>
/// <returns></returns>
private static string AddToResult(string s1, string s2)
{
var len = s1.Length - s2.Length;
int temp = 0;
StringBuilder sb = new StringBuilder();
for (int i = s1.Length - 1; i >= 0; i--)
{
int s;
if (i - len >= 0)
{
s = s1[i].CharToInt() + s2[i - len].CharToInt() + temp;
}
else
{
s = s1[i].CharToInt() + temp;
}
temp = 0;
while (s >= 10)
{
temp++;
s -= 10;
}
sb.Insert(0, s);
}
if (temp > 0)
{
sb.Insert(0, temp);
}
return sb.ToString();
}
/// <summary>
/// 字符轉換int
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
static int CharToInt(this char s)
{
switch (s)
{
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
default:
return 0;
}
}
}
}