大数处理问题(二)(大数相乘)
题意:两个大数相乘,求结果
在求解大数相乘问题时,可以先对大数处理问题(一)(大数相加)进行简化成如下:
对sum数组进行处理:
这样直接简化的数组的右对齐过程,思想简单,容易理解;
代码如下:
#include<iostream>
#include<string>
#include<stdio.h>
#include<string.h>
using namespace std ;
int main() {
char a[21] , b[21] ;
while(cin >>a >> b) {
int sum[21] = {0} ;
int lena = strlen(a) - 1 ;
int lenb = strlen(b) - 1 ;
int t = 20 ;
for(; lena >= 0 || lenb >= 0 ; lena--,lenb--)
sum[t--] = a[lena] - '0' + b[lenb] - '0' ;
for(int k = 20 ; k>= 1; k--) { //对sum数组进行处理
sum[k-1] += sum[k] / 10 ; //商进到前一位中
sum[k] = sum[k] % 10 ; //余数留在原位置
}
int start = 0 ;
while(start <= 20 && !sum[start]) //去除sum数组中多余的“0”
start++ ;
while(start<=20) //从左到右输出sum数组中的数值
cout << sum[start++] ;
cout << endl ;
}
return 0 ;
}理解大数相加算法之后,很容易过度到大数相乘:
只需多加一层循环即可,分析如下:
然后对sum数组进行处理进位,相应代码如下:
#include<iostream>
#include<string>
#include<stdio.h>
#include<string.h>
using namespace std ;
int main() {
char a[21] , b[21] ;
while(cin >>a >> b) {
int sum[21] = {0} ;
int lena = strlen(a) - 1 ;
int lenb = strlen(b) - 1 ;
int x = lena ;
for( ; lena >= 0 ; lena--)
for(int lenB = lenb , t = 20 - ( x - lena ); lenB >= 0 ; lenB--) //t用来控制竖式的缩进
sum[t--] = ( a[lena] - '0' ) * ( b[lenB] - '0' ) ;
for(int k = 20 ; k>= 1; k--) { //对sum数组进行处理
sum[k-1] += sum[k] / 10 ; //商进到前一位中
sum[k] = sum[k] % 10 ; //余数留在原位置
}
int start = 0 ;
while(start <= 20 && !sum[start]) //去除sum数组中多余的“0”
start++ ;
while(start<=20) //从左到右输出sum数组中的数值
cout << sum[start++] ;
cout << endl ;
}
return 0 ;
}
同样可以使用JAVA来实现,代码如下:
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in) ;
while(sc.hasNext()) {
BigInteger s = new BigInteger(sc.next()) ;
BigInteger t = new BigInteger(sc.next()) ;
s = s.multiply(t) ;
System.out.println(s);
}
}
}

浙公网安备 33010602011771号