C++高精度乘法模板

方法還是與高精度加法的方法差不多,列一個豎式,就可以發現其中的規律了。

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#define N 3001
using namespace std ;
int main ( )
{
    char a1 [ N ] , b1 [ N ] ;
    int a [ N ] , b [ N ] , c [ N ] , x ;
    memset ( a , 0 , sizeof ( a ) ) ;
    memset ( b , 0 , sizeof ( b ) ) ;
    memset ( c , 0 , sizeof ( c ) ) ;
    gets ( a1 ) ;
    gets ( b1 ) ;
    int lena = strlen ( a1 ) , lenb = strlen ( b1 ) ;
    for ( int i = 0 ; i < lena ; i ++ ) a [ lena - i ] = a1 [ i ] - 48 ;
    for ( int i = 0 ; i < lenb ; i ++ ) b [ lenb - i ] = b1 [ i ] - 48 ;
    for ( int i = 0 ; i <= lena ; i ++ ) 
    {
        x = 0 ;  //用來存放進位 
        for ( int j = 1 ; j <= lenb ; j ++ )
        {
            c [ i + j - 1 ] += a [ i ] * b [ j ] + x ;  
            x = c [ i + j - 1 ] / 10 ;
            c [ i + j - 1 ] %= 10 ;
        }   
        c [ i + lenb ] = x ;         //進位
    } 
    int lenc = lena + lenb ;
    while ( c [ lenc ] == 0 && lenc > 1 )  lenc -- ;   //刪除前導0
    for ( int i = lenc ; i > 0 ; i -- ) printf ( "%d" , c [ i ] ) ;
    return 0 ;
}

相關鏈接:

C++模板小站:
https://blog.csdn.net/ZJ_MRZ/article/details/80950647

C++快速冪模板:
https://blog.csdn.net/zj_mrz/article/details/80950616

C++高精度加法模板:
https://blog.csdn.net/zj_mrz/article/details/80948327

C++高精度減法模板:
https://blog.csdn.net/zj_mrz/article/details/80965324

發佈了45 篇原創文章 · 獲贊 60 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章