首页 > 代码库 > 大数相乘
大数相乘
#include <stdio.h>
#include "string.h" // strlen()
#include <stdlib.h> // malloc()/free()
void bigmutiply(const char *big1, const char *big2){
if (big1 == NULL || big2 == NULL) { return ;}
unsigned long b1 = strlen(big2);
unsigned long b2 = strlen(big2);
unsigned long total = b2+b1;
unsigned long *result = malloc( (b1+b2) * sizeof(unsigned long));
// 全部置为0
for (int i = 0; i<total; i++) { result[i] = 0;}
for (int i=0; i<b1; i++) {
for (int j = 0; j<b2; j++) {
// 把字符转化为数字
result[i+j+1] += (big1[i]-‘0‘)*(big2[j] -‘0‘);
}
}
for (int i = 0; i<total; i++) {
if (result[i]>10) {
result[i-1] += result[i]/10; // 除数
result[i] = result[i]%10; // 余数
}
}
if (result[0] == 0) {
for (int i = 1; i<total; i++) {
printf("%ld", result[i]);
}
}else{
for (int i = 0; i<total; i++) {
printf("%ld", result[i]);
}
}
free(result);
printf("\n");
}
int main(int argc, const char * argv[]) {
char *p1 = "112341234123412341234123412341234123412341";
char *p2 = "212341234123412341243564567867865342523413";
bigmutiply(p1, p2);
printf("Hello, World!\n");
return 0;
}
大数相乘