大数乘法是高手的必经之路
[Asm] 纯文本查看 复制代码 #define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void bigNum(char * str1, char *str2,char * res) {
int length1 = strlen(str1);//求str1长度
int length2 = strlen(str2);//求str2长度
char jieguo[2048] = { 0 };//缓冲区
for (int i = length2 - 1,m=0; i >= 0; i--,m++) {//将str2每一位分别与str1每一位相乘,关键是相乘后的数,从后往前计数str2的第m位与str1的第n位相乘后加上jieguo[m+n]之前的数并存放在jieguo[m+n]中,判断jieguo[m+n]是否进位。
for (int j = length1 - 1,n = 0; j >= 0; j--,n++) {
int temp = jieguo[m + n]+(str2[i] - '0') * (str1[j] - '0');
jieguo[m + n + 1] += temp / 10;
jieguo[m + n] = temp % 10;
}
}
//对调缓冲区,存入res字符串数组中。
int i = 2047;
while (jieguo[i] == 0) {
i--;
}
for (int k = i,r=0; k >= 0; k--,r++) {
res[r] = (char)jieguo[k] + 48;
}
}
void maintt() {
char str1[1024];
char str2[1024];
scanf("%s", str1);
scanf("%s", str2);
char res[2048] = { 0 };
bigNum(str1, str2, res);
printf("%s", res);
system("pause");
}
////方法二,递归
void bignum2(char * str1, char *str2,char * arr, int length) {//arr为结果数组
if (length == 0) {
int i = 2047;
while (arr[i] == 0) {
i--;
}
for (int j = 0; j <= i / 2; j++) {
char temp = arr[j]+'0';
arr[j] = arr[i - j]+'0';
arr[i - j] = temp;
}
return;
}
else {
int length1 = strlen(str1);
int length2 = strlen(str2);
for (int i = length1 - 1, m = 0; i >= 0; i--, m++) {
int temp = arr[m + length2 - length] + (str2[length - 1] - '0')*(str1[i] - '0');
arr[m + length2 - length] = temp % 10;
arr[m + length2 - length + 1] += temp / 10;
}
bignum3(str1, str2,arr, length - 1);
}
}
void main() {
char str1[1024];
char str2[1024];
char arr[2048] = { 0 };
scanf("%s", str1);
scanf("%s", str2);
char res[2048] = { 0 };
bignum3(str1, str2, res, strlen(str2));
printf("%s", res);
system("pause");
} |