加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

大数处理问题(二)(大数相乘)

发布时间:2020-12-14 03:01:05 所属栏目:大数据 来源:网络整理
导读:题意:两个大数相乘,求结果 在求解大数相乘问题时,可以先对 大数处理问题(一)(大数相加) 进行简化成如下: 对sum数组进行处理: 这样直接简化的数组的右对齐过程,思想简单,容易理解; 代码如下: #includeiostream#includestring#includestdio.h#inc

题意:两个大数相乘,求结果

在求解大数相乘问题时,可以先对大数处理问题(一)(大数相加)进行简化成如下:


对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);
		}
	}
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读