下一篇博客---->大整数运算包的实现(Java)(2) --快速幂取模、最大公约数、乘法逆元、素数判定、生成大素数
一、大数加法
public static String Add(String one,String two) {
if(one.equals("0"))
return two;
if(two.equals("0"))
return one;
int length1=one.length();
int length2=two.length();
char[] Long=null,Short=null;
int i,max=0,min=0,carry=0,num1,num2,front1=0,front2=0,isNegative1=0,isNegative2=0,oneLong=0;
if(one.charAt(0)=='-') {
isNegative1=1;
front1++;
length1--;
}
if(two.charAt(0)=='-') {
isNegative2=1;
front2++;
length2--;
}
if(length1>length2) {
max=one.length();
min=two.length();
Long=one.toCharArray();
Short=two.toCharArray();
oneLong=1;
}
else if(length1<length2){
max=two.length();
min=one.length();
Long=two.toCharArray();
Short=one.toCharArray();
}
else {
int j,k;
for(j=front1,k=front2;j<one.length();j++,k++) {
if(one.charAt(j)>two.charAt(k)) {
max=one.length();
min=two.length();
Long=one.toCharArray();
Short=two.toCharArray();
oneLong=1;
break;
}else if(one.charAt(j)<two.charAt(k)){
max=two.length();
min=one.length();
Long=two.toCharArray();
Short=one.toCharArray();
break;
}
}
if(j==one.length()) {
if(isNegative1==isNegative2) {
max=one.length();
min=two.length();
Long=one.toCharArray();
Short=two.toCharArray();
}else {
return "0";
}
}
}
int[] result=new int[length1>length2?length1+1:length2+1];
String number="";
if(isNegative1==isNegative2) {
for(i=0;min>front1;i++) {
num1=Long[--max]-48;
num2=Short[--min]-48;
result[i]=(num1+num2+carry)%10;
carry=(num1+num2+carry)/10;
}
while (max>front1) {
num1=Long[--max]-48;
result[i++]=(num1+carry)%10;
carry=(num1+carry)/10;
}
if(carry==1)
result[i]=1;
if(isNegative1==1)
number+='-';
if(result[i]!=0)
number+=String.valueOf(result[i--]);
else
i--;
for(;i>=0;i--)
number+=String.valueOf(result[i]);
}else {
if(oneLong==1) {
length1=front2;
length2=front1;
if(isNegative1==1)
number+="-";
}else {
length1=front1;
length2=front2;
if(isNegative2==1)
number+="-";
}
for(i=0;min>length1;i++) {
num1=Long[--max]-48;
num2=Short[--min]-48;
result[i]=(num1-num2+10+carry)%10;
if(num1-num2+carry<0)
carry=-1;
else
carry