要求不少于35位数,是超大数乘法吧,找了个示例,未严格测试,供参考:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLEN 256
int _isNum(const char *num)
{
for (; *num != 0; num++)
{
if ((*num > '9') || (*num < '0'))
{
printf("输入的数含有非法的字符!!!\n");
return 0;
}
}
return 1;
}
void _addCarry(int *result, int count)
{
int i;
for (i=(count-1); i>0; i--)
{
int tmp = result[i];
if (tmp >= 10)
{
result[i]
= tmp % 10;
result[i-1] += tmp / 10;
}
else if (tmp < 0)
{
result[i]
+= 10;
result[i-1] -= 1;
}
}
}
char* _NumToStr(int *num, int count, char ch)
{
int i;
for (; count>1 && *num==0; num++, count--) NULL;
if (*num==0) ch='+';
char *resultStr = (char*)malloc((count+2) * sizeof(char));
memset(resultStr, 0, (count+1) * sizeof(char));
if (ch=='-')
{
strcat(resultStr, "-");
}
char sz[5];
for (i=0; i<count; i++)
{
itoa(num[i], sz, 10);
strcat(resultStr, sz);
}
return resultStr;
}
char* _imulBigNum(char *num1, char *num2)
{
int i, j;
if (*num1==0 || *num2==0) return NULL;
char ch='+', ch1='+', ch2='+';
if (*num1=='-')
{
ch1 = '-';
num1++;
}
if (*num2=='-')
{
ch2 = '-';
num2++;
}
if (!_isNum(num1)) return NULL;
if (!_isNum(num2)) return NULL;
ch = (ch1==ch2) ? '+' : '-';
int num1Len = strlen(num1);
int num2Len = strlen(num2);
if ((num1Len > MAXLEN) || (num2Len > MAXLEN))
{
printf("输入的数的数位长度超出范围(<=%d)\n", MAXLEN);
return NULL;
}
int resultLen = num1Len + num2Len - 1;
int *result = (int*)malloc(resultLen * sizeof(int));
memset(result, 0, resultLen * sizeof(int));
for (i=num1Len-1; i>=0; i--)
{
for (j=num2Len-1; j>=0; j--)
{
result[i+j] += (num1[i] - '0') * (num2[j] - '0');
}
}
_addCarry(result, resultLen);
char *resultStr = _NumToStr(result, resultLen, ch);
free(result);
return resultStr;
}
main()
{
char str1[MAXLEN+1], str2[MAXLEN+1];
char *num1=str1, *num2=str2, *result;
int i;
printf("被乘数:");
gets(num1);
printf("乘数:");
gets(num2);
for (i=0; (*num1=='0' && *(num1+1)!=0); num1++) NULL;
for (i=0; (*num2=='0' && *(num2+1)!=0); num2++) NULL;
result = _imulBigNum(num1, num2);
if (result != NULL)
{
printf("(%s) * (%s) = %s\n", num1, num2, result);
free(result);
}
}