C++高精度乘法模板

方法还是与高精度加法的方法差不多,列一个竖式,就可以发现其中的规律了。

#include 
#include 
#include 
#include 
#include 
#include 
#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

转载于:https://www.cnblogs.com/zj-mrz/p/10122474.html

你可能感兴趣的:(C++高精度乘法模板)