两个大数目字的相乘
两个大数字的相乘
public void testMul() throws Exception{
String p1 = "123456789012345678901234123456789012345678901234";//"123456789012345678901234";
String p2 = "987654321098765432109876543210987654123456789012345678901234";//"987654321098765432109876543210987654";
int ASCII = 48;
char[] result = new char[p1.length() + p2.length()];
for(int i = 0; i < result.length; i++){
result[i] = '0';
}
char ctemp = ' ';
char[] pc1 = p1.toCharArray();
for(int i = 0 ; i < pc1.length/2; i++){
ctemp = pc1[i];
pc1[i] = pc1[pc1.length - 1 - i];
pc1[pc1.length - 1 - i] = ctemp;
}
char[] pc2 = p2.toCharArray();
for(int i = 0 ; i < pc2.length/2; i++){
ctemp = pc2[i];
pc2[i] = pc2[pc2.length - 1 - i];
pc2[pc2.length - 1 - i] = ctemp;
}
int temp = 0;//临时结果
int step = 0;//进位
int time = 0;//次数
int bit = 0;//位数
for(char c1 : pc1){
time = bit;
for(char c2 : pc2){
temp = (c1 - ASCII) * (c2 - ASCII);
temp = temp + result[time] -ASCII;
if(temp > 9){//进位
int i = 0;
do{
result[time + i] = (char)(temp % 10 + ASCII);
step = (temp - temp % 10) / 10;
i++;
temp = result[time + i] - ASCII + step;
}while(temp > 9);
result[time + i] = (char)(temp + ASCII);
}else{
result[time] = (char)(temp + ASCII);
}
time++;
}
bit++;
}
System.out.println("##############################");
System.out.print(p1 + " x " + p2 + " = ");
for(int i = result.length - 1; i >= 0; i--){
System.out.print(result[i]);
}
System.out.println();
System.out.println("##############################");
}
public void testMul() throws Exception{
String p1 = "123456789012345678901234123456789012345678901234";//"123456789012345678901234";
String p2 = "987654321098765432109876543210987654123456789012345678901234";//"987654321098765432109876543210987654";
int ASCII = 48;
char[] result = new char[p1.length() + p2.length()];
for(int i = 0; i < result.length; i++){
result[i] = '0';
}
char ctemp = ' ';
char[] pc1 = p1.toCharArray();
for(int i = 0 ; i < pc1.length/2; i++){
ctemp = pc1[i];
pc1[i] = pc1[pc1.length - 1 - i];
pc1[pc1.length - 1 - i] = ctemp;
}
char[] pc2 = p2.toCharArray();
for(int i = 0 ; i < pc2.length/2; i++){
ctemp = pc2[i];
pc2[i] = pc2[pc2.length - 1 - i];
pc2[pc2.length - 1 - i] = ctemp;
}
int temp = 0;//临时结果
int step = 0;//进位
int time = 0;//次数
int bit = 0;//位数
for(char c1 : pc1){
time = bit;
for(char c2 : pc2){
temp = (c1 - ASCII) * (c2 - ASCII);
temp = temp + result[time] -ASCII;
if(temp > 9){//进位
int i = 0;
do{
result[time + i] = (char)(temp % 10 + ASCII);
step = (temp - temp % 10) / 10;
i++;
temp = result[time + i] - ASCII + step;
}while(temp > 9);
result[time + i] = (char)(temp + ASCII);
}else{
result[time] = (char)(temp + ASCII);
}
time++;
}
bit++;
}
System.out.println("##############################");
System.out.print(p1 + " x " + p2 + " = ");
for(int i = result.length - 1; i >= 0; i--){
System.out.print(result[i]);
}
System.out.println();
System.out.println("##############################");
}