大整数相乘

处理大整数相乘的办法很多,我这里贴一种最简单实现,通过字符数组去接收和输入大整数。题目要求如下:

大整数相乘_第1张图片

代码如下:

// 2015.9.15 华为.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"



#include <stdio.h>
#include <string.h>

#define MAXLENGTH 1024
#define M 100 /*输出不超过100位大数乘积*/

void BigNumOfMul(char *FirstNum,char *SecondNum,
                 int FirstNumLen,int SecondNumLen) 
{
    int i,j,temp,tt;
    i = 0;
    j = 0;
    int num=0;
    int LowBitNum = 0;
    int FirstNumFlag = 1;
    int SecondNumFlag = 1;
    int BigNumOfMulResult[M];
    char *FirstNumTemp = FirstNum;
    char *SecondNumTemp = SecondNum;

    memset(BigNumOfMulResult,0,sizeof(BigNumOfMulResult));
    /*1.需要考虑负数的情况*/
#if 1
    if(FirstNum[0] == '-') {
        FirstNumFlag = -1;
        j = 1;
        strcpy(FirstNumTemp,(FirstNum+1));
        FirstNumLen = FirstNumLen - 1;
    }

    if(SecondNum[0] == '-') {
        SecondNumFlag = -1;
        i = 1;
        strcpy(SecondNumTemp,(SecondNum+1));
        SecondNumLen = SecondNumLen - 1;
    }
#endif 

    for(i = 0;i<SecondNumLen;i++)
    {
        temp=0;
        for(j = 0;j<FirstNumLen;j++)
        {    
            /*2.最低位开始计算*/
            LowBitNum =(FirstNumTemp[FirstNumLen-1-j]-'0')*(SecondNumTemp[SecondNumLen-1-i]-'0')+temp;
            if(0 == LowBitNum)    
                continue; 
            num = j+i;        
            tt = BigNumOfMulResult[num]+LowBitNum;    
            BigNumOfMulResult[num] = tt%10;    
            temp = tt/10;
        }
        if( temp > 0 )
        {
            BigNumOfMulResult[++num] += temp;
        }
    }
    /*3.输出结果*/
    /*负数*/
    if((SecondNumFlag*FirstNumFlag) == -1) {
        printf("-");
    }
    for(i=num;i>=0;i--) {                
        printf("%d",BigNumOfMulResult[i]);
    }

    printf("\n");
}


int main()
{
    char a[MAXLENGTH],b[MAXLENGTH];
    /*1.当成字符串来操作*/
    scanf("%s %s",&a,&b);

    int FirstNumLen = strlen(a);
    int SecondNumLen = strlen(b);
    /*2.大整数相乘*/
    BigNumOfMul(a,b,FirstNumLen,SecondNumLen);

    return 0;
}

你可能感兴趣的:(大整数相乘)