アルゴリズム導論@大数乗算
テーマの要求:2つの大きい数を乗算します.2つの大きな数を文字列で入力し、結果を文字列に保存します.
注意:文字列回転整数1-'0'
処理方法一:
処理方法2:
注意:文字列回転整数1-'0'
処理方法一:
#include"cheng.h"
#define MAX 100
//
int main()
{
char *a = (char*)malloc(sizeof(char)), *b = (char*)malloc(sizeof(char));
char *res = (char*)malloc(sizeof(char));
char *m = (char*)malloc(sizeof(char)), *n = (char*)malloc(sizeof(char));
int carry = 0;
//
cout << " :" << endl;
cin >> a;
cin >> b;
//
for (int i = 0; i < strlen(a); i++)
{
m[i] = a[strlen(a) - i - 1];
}
m[strlen(a)] = NULL;
for (int i = 0; i < strlen(b); i++)
{
n[i] = b[strlen(b) - i - 1];
}
n[strlen(b)] = NULL;
//
for (int i = 0; i < strlen(a) + strlen(b); i++)
{
res[i] = 0;
}
//
for (int i = 0; i < strlen(a) ; i++)
{
for (int j = 0; j < strlen(b); j++)
{
res[i + j] += (m[i] - '0')*(n[j] - '0');
}
}
// ,
for (int i = 0; i < strlen(a)+strlen(b); i++)
{
char temp = res[i];
res[i] = (res[i]+carry)% 10;
carry = (temp + carry) / 10;
}
// 0,
if (res[strlen(a) + strlen(b) - 1] == 0)
{
for (int i = strlen(a) + strlen(b) - 2; i >= 0; i--)
{
printf("%d",res[i]);
}
}
else
{
for (int i = strlen(a) + strlen(b) - 1; i >= 0; i--)
{
printf("%d", res[i]);
}
}
system("pause");
return 0;
}
処理方法2:
#include"cheng.h"
#define MAX 100
//
int main()
{
// a,b
char *a = (char*)malloc(sizeof(char));
char *b = (char*)malloc(sizeof(char));
// res
char *res = (char*)malloc(sizeof(char));
//
int carry = 0;
//m,n a,b
int m[MAX], n[MAX];
// :
cout << " :" << endl;
cin >> a;
cin >> b;
// ,
for (int i = 0; i < strlen(a); i++)
{
m[i] = a[strlen(a)-i-1]-'0';
//
//m[i]=*(a+strlen(a)-i-1)-'0';
}
for (int i = 0; i < strlen(b); i++)
{
n[i] = b[strlen(b) - i - 1]-'0';
//
//n[i]=*(b+strlen(b)-i-1)-'0';
}
// result
int result[MAX] = { 0 };
for (int i = 0; i < strlen(a); i++)
{
for (int j = 0; j < strlen(b); j++)
{
result[i + j] += m[i] * n[j];
}
}
// ,
int temp = 0;
for (int i = 0; i < strlen(a) + strlen(b); i++)
{
temp = result[i];
result[i] = (result[i] + carry) % 10;
carry = (temp + carry) / 10;
}
/***************
if (result[strlen(a) + strlen(b) - 1] == 0)
{
for (int i = strlen(a) + strlen(b) - 2; i >= 0; i--)
{
cout << result[i] ;
}
}
else
{
for (int i = strlen(a) + strlen(b) - 1; i >= 0; i--)
{
cout << result[i];
}
}
***************/
//
// , 0,
if (result[strlen(a) + strlen(b)-1] == 0)
{
int index = 0;
for (int i = strlen(a) + strlen(b)-2; i >=0; i--)
{
res[index++] = result[i] + '0';
}
res[index] = NULL;
}
else
{
int index = 0;
for (int i = strlen(a) + strlen(b) - 1; i >= 0; i--)
{
res[index++] = result[i] + '0';
}
res[index] = NULL;
}
printf("%s", res);
system("pause");
return 0;
}