最新闲时搞了下大数相加相乘的算法.
我把多位相乘分解成了异位后的单位相乘后相加.具体如下
/*** 多位相乘
* @param num1
* @param num2
* @return
*/
public String multiply(String num1, String num2) {
int[] array2 = parseCharArray(num2.toCharArray());
String sum = "0";
for (int i = array2.length - 1; i >= 0 ; i--) {
sum = plus(sum, multiply(num1, array2[i]));
num1 += "0";
}
return sum;
}
/**
* 单位相乘
* @param num1
* @param num2
* @return
*/
public String multiply(String num1, int num2) {
// String ret = num1;
// for (int i = 0; i < num2 - 1; i++) {
// ret = plus(ret, num1);
// }
// return ret;
int[] array = parseCharArray(num1.toCharArray());
StringBuilder stringBuilder = new StringBuilder();
int plus = 0;
int sum = 0;
for (int i = array.length - 1; i >= 0; i--) {
sum = array[i] * num2 + plus;
plus = sum / 10;
sum %= 10;
stringBuilder.append(sum);
}
if (plus != 0) {
stringBuilder.append(plus);
}
return stringBuilder.reverse().toString();
}
/**
* 大数相加
* @param num1
* @param num2
* @return
*/
public String plus(String num1, String num2) {
char[] num1Array = null;
char[] num2Array = null;
if (num1.length() > num2.length()) {
num1Array = num1.toCharArray();
num2Array = num2.toCharArray();
} else {
num1Array = num2.toCharArray();
num2Array = num1.toCharArray();
}
int[] array1 = parseCharArray(num1Array);
int[] array2 = parseCharArray(num2Array);
for (int i = 0; i < num2Array.length; i++) {
array2[i] = num2Array[i] - '0';
}
StringBuilder stringBuilder = new StringBuilder();
int plus = 0;
int sum = 0;
int minLen = array2.length;
int maxLen = array1.length;
for (int i = minLen - 1; i >= 0; i--) {
sum = array1[maxLen - minLen + i] + array2[i] + plus;
plus = sum / 10;
sum %= 10;
stringBuilder.append(sum);
}
for (int i = maxLen - minLen - 1; i >= 0; i--) {
sum = array1[i] + plus;
plus = sum / 10;
sum %= 10;
stringBuilder.append(sum);
}
if (plus != 0) {
stringBuilder.append(plus);
}
return stringBuilder.reverse().toString();
}
算法较为简单,测试了一下:
public static void main(String[] args) {
String str1 = getBigNumber(10000);
String str2 = getBigNumber(10000);
// System.out.println("str1:" + str1);
// System.out.println("str2:" + str2);
long current = System.currentTimeMillis();
// String plus = new BigNumber().plus(str1, str2);
// String plus = new BigNumber().multiply(str1, 3);
String plus = new BigNumber().multiply(str1, str2);
System.out.println("use:" + (System.currentTimeMillis() - current));
System.out.println("plus:" + plus);
}
一个10000位的大数乘以一个10000位的大数,大约使用了
use:7203
平均使用7s,性能算是一般的,还没看过其他大牛写的,改天借鉴学习下.
以上文章属本人原创,如转载请尊重作者,注明出处,谢谢!
http://blog.csdn.net/u012803801/article/details/15378515