/* 编译时请关闭优化 */ /* 主要思路是模拟打竖式 */ #include <stdio.h> #include <string.h> #define U (4096) /* 因数的最大位数 */ #define RU (2 * U + 1) long calculate_mul(char *longerone, char *shorterone, unsigned int *buffer){ /* 使用 unsigned int 是为了减少循环次数 */ long longerpos,shorterpos; long longerlen; long bufferpos,buffersubpos; long loop,loop_1; /* 循环计数器 */ longerlen = strlen(longerone); longerpos = longerlen – 1; shorterpos = strlen(shorterone) – 1; buffersubpos = RU – 1; bufferpos = buffersubpos; memset(buffer, 0, RU); /* 准备工作 */ for(loop = 0;loop <= longerpos;++loop){ if(longerone[loop] >= ‘0’ && longerone[loop] <= ‘9’)longerone[loop] -= ‘0’; else return 1; } for(loop = 0;loop <= shorterpos;++loop){ if(shorterone[loop] >= ‘0’ && shorterone[loop] <= ‘9’)shorterone[loop] -= ‘0’; else return 1; } /* 主要代码 */ for(loop = 1; ; ++loop){ if(loop == 47721855){ for(loop_1 = RU – 1; loop_1 != 0; –loop_1){ if(buffer[loop_1] > 9){ buffer[loop_1 – 1] += (buffer[loop_1] – (buffer[loop_1] % 10)) / 10; buffer[loop_1] = buffer[loop_1] % 10; } } loop = 1; } buffer[bufferpos] += (longerone[longerpos] * shorterone[shorterpos]); –longerpos; –bufferpos; if(longerpos == -1){ if(shorterpos == -1) break; else{ longerpos = longerlen – 1; bufferpos = –buffersubpos; –shorterpos; } } } for(loop_1 = RU – 1; loop_1 != 0; –loop_1){ if(buffer[loop_1] > 9){ buffer[loop_1 – 1] += (buffer[loop_1] – (buffer[loop_1] % 10)) / 10; buffer[loop_1] = buffer[loop_1] % 10; } } for(loop = 0; loop != RU; ++loop){ if(buffer[loop] != 0){ loop_1 = 0; for(; loop != RU; ++loop){ buffer[loop_1] = buffer[loop] + ‘0’; ++loop_1; } buffer[loop_1] = ‘/0’; break; } } return 0; } int main(void){ char num1[U];char *num1_ptr; char num2[U];char *num2_ptr; long loop; unsigned int result[RU]; char result2[RU]; long return_num; printf(“/nFirst Positive Integer : “); scanf(“%s”, num1); num1_ptr = num1; printf(“/nSecond Positive Integer : “); scanf(“%s”, num2); num2_ptr = num2; if(strlen(num1_ptr) <= strlen(num2_ptr)){ return_num = calculate_mul(num2_ptr, num1_ptr, result); }else{ return_num = calculate_mul(num1_ptr, num2_ptr, result); } if(return_num == 0){ printf(“/nRESULT:”); for(loop = 0; loop != RU; ++loop) result2[loop] = result[loop];/* 将 unsigned int 数组转录至串中,便于输出 */ printf(result2); }else{ printf(“/nERROR:%ld”, return_num); } return return_num; }
[C语言]大整数乘法
原文作者:大整数乘法问题
原文地址: https://blog.csdn.net/ho121/article/details/4625208
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
原文地址: https://blog.csdn.net/ho121/article/details/4625208
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。