swustoj大整数乘法(0447)

    xiaoxiao2021-04-12  35

    在一些应用中,特别是现在的密码学中,常常需要用超过100位的整数来做乘法,以此来对数据加密。  现在有两个小于等于100位的大整数a和b(位数相同),请写程序计算出这两个大整数乘积的结果。 Description 输入有三行  第一行是大整数位数  第一个大整数  第二个大整数 Input 两个大整数的结果 Output 1 2 3 10 1111111111 1111111111 Sample Input 1 1234567900987654321 Sample Output

    #include<iostream> #include<algorithm> #include<string.h> #include<stdio.h> using namespace std; void Compute(char *a, char *b, char *c) { int n, m; m = strlen(a) - 1; n = strlen(b) - 1; for (int i = m; i >= 0; i--) { a[i] -= '0'; } for (int i = n; i >= 0; i--) { b[i] -= '0'; } c[m + n + 2] = '\0'; long carry = 0; long sum; int j; for (int i = m + n; i >= 0; i--)//每次只算出最后一位数并且保存上一位数在进行下一次运算 { sum = carry; if ((j = (i - m)) < 0) { j = 0; } for (; j <= i&&j <= n; j++) { sum += a[i - j] * b[j]; } c[i + 1] = sum % 10 + '0'; carry = sum / 10; } c[0] = carry + '0'; } int main() { int k; char str1[105]; char str2[105]; char ans[10000]; while(cin >> k)//位数(虽然没什么用)QAQ { scanf("%s%s", str1, str2); //cout << str1 << endl << str2 << endl; Compute(str1, str2, ans); if(ans[0]!='0')//判断一下第一个是否为0,是就不输出ans[0] printf("%s", ans); else { for (int i = 1; i < strlen(ans); i++) { cout << ans[i]; } } cout << endl; } return 0; }

    转载请注明原文地址: https://ju.6miu.com/read-667827.html

    最新回复(0)