企业博客网bokee.net www.bokee.net http://zmdxyboyandy.blog.bokee.net/  大数乘法C语言实现 打印此页

大数乘法C语言实现

http://zmdxyboyandy.blog.bokee.net    2007-11-18

大数乘法:

按照32位机器表示法,最多可计算结果为32位以内的数的乘法,否则会溢出;

借助字符串转换,可以解决这一问题;

#include<stdio.h>
#include<string.h>
#define MAX 100
#define MUX 200
char A[MAX];
char B[MAX];
int reverse(char str[],int len){
  char temp;
  int i;
  for(i=0;i<(len+1)/2;i++){
    temp=str[i];
    str[i]=str[len-i-1];
    str[len-i-1]=temp;
  }
  return 0;
}
int main(void){
  char *ptr;
  int increase=0;
  ptr=A;
  int i=0;
  int j=0;
  int temp=0;
  int add=0;
  printf("input the first number:");
  scanf("%s",ptr);
  ptr=B;
  printf("\ninput the second number:");
  scanf("%s",ptr);
  printf("%s*%s=",A,B);
  reverse(A,strlen(A));
  reverse(B,strlen(B));
  char result[MUX];//array to store the result;
  for(i=0;i<MUX-1;i++)
    result[i]='0';//initial the array,every bit is 0;
  for(i=0;i<strlen(A);i++){
    increase=0;
    for(j=0;j<strlen(B);j++){
      temp=(A[i]-48)*(B[j]-48);
      add=(temp+increase+(result[i+j]-48))%10;
      increase=(temp+increase+(result[i+j]-48))/10;
      result[i+j]=add+48;
      if(j==strlen(B)-1&&increase>0)
        result[i+j+1]=increase+48;  
    }//for j
  
  }//for i
  int k=0;
  char temper;
  reverse(result,MUX-1);//attention :MUX-1
  int writeflag=0;
  printf("\nthe result is:");
  for(i=0;i<MUX;i++){
    if(result[i]!='0') writeflag=1;
    if(writeflag==1)
      printf("%c",result[i]);
  }
  printf("\n");
  return 0;
}//return main