大数乘法
【摘要】 #include <stdio.h>#include <string.h> #define N 1000 void charstoint(int a[], char s[]){ int i; int len = strlen(s); memset(a,0,4*N); //整型占4个字节 for (i=0; i<len; i++) { //...
#include <stdio.h>
#include <string.h>
#define N 1000
void charstoint(int a[], char s[])
{
int i;
int len = strlen(s);
memset(a,0,4*N); //整型占4个字节
for (i=0; i<len; i++)
{
//不考虑负数与非数字字符的情况
a[len-1-i] = s[i] - '0'; //将每一个字符转化为数字逆序存放在整型数组中,例如字符串 123456 -> a[0] = 6,a[1] = 5, ...a[5] = 1;
}
}
void multiply(int a[], int b[], int c[])
{
int i,j;
memset(c,0,2*N*4); //c数组存放两个大数相乘的结果。
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 i,j = 2*N-1;
int a[N],b[N],c[2*N];
char s1[N],s2[N];
printf("input the first number:");
gets(s1);
printf("input the second number:");
gets(s2);
charstoint(a,s1);
charstoint(b,s2);
multiply(a,b,c);
while(c[j]==0) //去掉多余的0
{
j--;
}
for (i=j; i>=0; --i) //打印结果
{
printf("%d",c[i]);
}
printf("\n");
return 0;
}
文章来源: blog.csdn.net,作者:悦来客栈的老板,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/qq523176585/article/details/11567291
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)