POJ2389 —— 高精度乘法
直接上代码了:
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<cmath> #include<queue> #include<vector> #include<map> #include<string> #include<set> #define LL long long #define MAX(a,b) (a>b?a:b) #define MIN(a,b) (a<b?a:b) using namespace std; char s[50]; int a[50],b[50],c[100]; int main() { int lena = 0, lenb = 0; memset(a,0,sizeof(a)); memset(b,0,sizeof(b)); memset(c,0,sizeof(c)); gets(s); for(int i = strlen(s)-1; i>=0; i--) a[lena++] = s[i]-'0'; gets(s); for(int i = strlen(s)-1; i>=0; i--) b[lenb++] = s[i] - '0'; for(int i = 0; i<50; i++) { int last = 0; for(int j = 0; j<50; j++) { c[i+j] += a[i]*b[j]; c[i+j] += last; last = c[i+j]/10; c[i+j] = c[i+j]%10; } } int t = 99; while(!c[t]) t--; while(t>=0) printf("%d",c[t--]); putchar('\n'); return 0; }
顺便附上高精度加法的函数:
//高精度加法 void highplus(char a[],char b[],char c[])//调用前必须memset {//将a+b存到c中,直接输出,但c是字符型,要整形则简修改即可 char ch; int la = strlen(a),lb = strlen(b); for(int i = 0;i<=(la-1)/2;i++)//将a和b位数倒转,以便逐位相加;同时-‘0’转成整形 { ch = a[i]-'0'; a[i] = a[la-1-i]-'0'; a[la-1-i] = ch; } for(int i = 0;i<=(lb-1)/2;i++) { ch = b[i]-'0'; b[i] = b[lb-1-i]-'0'; b[lb-1-i] = ch; } for(int i = 0;i<100;i++)//这里的100根据调用函数而修改 { //逐位计算,依照加法竖式 c[i] += b[i]+a[i]; c[i+1] += c[i]/10; c[i] %= 10; } int i = 99;//若精度不同记得修改 while(!c[i]) i--;//跳过无用的0; for(int j = 0;j<=i/2;j++)//将c再换成字符型,并再倒叙,使其成为正常数 { //记住要经过中间数,否则中间一个将没有转成字符型,所以用<=(len-1)/2 ch = c[j]+'0'; c[j] = c[i-j]+'0'; c[i-j] = ch; } }