链接地址:http://blog.csdn.net/jianzhibeihang/article/details/4948267
先来个简单的但是时间复杂度:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 100
/*
*将在数组中保存的字符串转成数字存到int数组中
*/
void getdigits(int *a,char *s)
{
int i;
char digit;
int len = strlen(s);
//对数组初始化
for(i = 0; i < N; ++i)
*(a + i) = 0;
for(i = 0; i < len; ++i){
digit = *(s + i);
*(a + len - 1 - i) = digit - '0';//字符串s="12345",因此第一个字符应该存在int数组的最后一个位置
}
}
/*
*将数组a与数组b逐位相乘以后存入数组c
*/
void multiply(int *a,int *b,int *c)
{
int i,j;
//数组初始化
for(i = 0; i < 2 * N; ++i)
*(c + i) = 0;
/*
*数组a中的每位逐位与数组b相乘,并把结果存入数组c
*比如,12345*12345,a中的5与12345逐位相乘
*对于数组c:*(c+i+j)在i=0,j=0,1,2,3,4时存的是5与各位相乘的结果
*而在i=1,j=0,1,2,3,4时不光会存4与各位相乘的结果,还会累加上上次相乘的结果.这一点是需要注意的!!!
*/
for(i = 0; i < N; ++i)
for(j = 0; j < N; ++j)
*(c + i + j) += *(a + i) * *(b + j);
/*
*这里是移位、进位
*/
for(i = 0; i < 2 * N - 1; ++i)
{
*(c + i + 1) += *(c + i)/10;//将十位上的数向前进位,并加上原来这个位上的数
*(c + i) = *(c + i)%10;//将剩余的数存原来的位置上
}
}
int main()
{
int a[N],b[N],c[2*N];
char s1[N],s2[N];
int j = 2*N-1;
int i;
printf("input the first number:");
scanf("%s",s1);
printf("/ninput the second number:");
scanf("%s",s2);
getdigits(a,s1);
getdigits(b,s2);
multiply(a,b,c);
while(c[j] == 0)
j--;
for(i = j;i >= 0; --i)
printf("%d",c[i]);
printf("/n");
return 0;
}
接着来个相对高效点的:
/**************************************
算法复杂度为:O(longhta*longthb)
longtha为乘数的位数
longhtb为被乘数的位数
***************************************/
#include <stdio.h>
#include <string.h>
#include <conio.h>
#define LEN 1000
void mult(char [],char [],char []);
main()
{
char op1[LEN],op2[LEN],op3[LEN*2-1];
scanf("%s%s",op1,op2);
mult(op1,op2,op3);
printf("%s\n",op3);
getch();
return 0;
}
void reverse(char a[])
{
int longth=strlen(a);
int i;
for(i=0;i<longth/2;i++){
char t;
t=a[i];
a[i]=a[longth-i-1];
a[longth-i-1]=t;
}
}
void mult(char op1[LEN],char op2[LEN],char ans[LEN*2-1])
{
char top1[LEN];
char top2[LEN];
strcpy(top1,op1);
strcpy(top2,op2);
reverse(top1);
reverse(top2);
int k;
int top1s=strlen(top1);
int top2s=strlen(top2);
for(k=0;k<top1s+top2s;k++){
ans[k]='0';
}
int i,j;
int jw,ys;
int longth;
for(j=0;j<top2s;j++){
jw=0;
for(i=0;i<top1s;i++){
ys=((top1[i]-'0')*(top2[j]-'0')+jw+ans[i+j]-'0')%10;
jw=((top1[i]-'0')*(top2[j]-'0')+jw+ans[i+j]-'0')/10;
ans[i+j]=ys+'0';
}
if(jw>0){
ans[i+j]=jw+'0';
}
}
longth=i+j-1;
if(jw>0)
ans[longth++]=jw+'0';
ans[longth]='\0';
reverse(ans);
}
这两个例子都是保留十进制的,我们项目需要的是要十六进制的,所以我们只需要很简单的求得取余和进位的时候把十替换成256