本帖最后由 ba21 于 2023-1-24 21:12 编辑
python 的大数相乘使用的是(算法)所以还真不慢。
闲着用弄弄,重在参与:
C代码#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void getNewNumber(char *a, char *b);
char *MultipyBigNumber(char *a, char *b);
long long mod(char *divisor, long long number);
void swap(char *a, char *b, int i);
int main()
{
char a[] = "51562165415643212316";
char b[] = "52213412312166548821";
int number = 998244353;
getNewNumber(a, b);
printf("%lld\n", mod(MultipyBigNumber(a,b), number));
return 0;
}
// 获取最小乘积所需要的被乘数和乘数
void getNewNumber(char *a, char *b)
{
int i;
for (i = 0; i < strlen(a); i++)
{
if (a[i] > b[i])
{
swap(a, b, i);
}
}
}
// 大数相乘
char *MultipyBigNumber(char *a, char *b)
{
int i, j, x, bitLeft, bitRight;
int lenA = strlen(a);
int lenB = strlen(b);
int len = lenA + lenB;
char *arr;
arr = (char*)malloc(sizeof(char)*(len+1));
arr[len] = '\0';
arr = &arr[len];
lenA--;
lenB--;
i = x = 0;
while(i < len - 1 || x != 0)
{
for(j = 0; j <= i; j++)
{
bitLeft = lenA - i + j;
bitRight = lenB - j;
if(bitLeft >= 0 && bitRight >= 0)
{
x += (a[bitLeft] - '0') * (b[bitRight] - '0');
}
}
*(--arr) = x % 10 + '0';
x /= 10;
i++;
}
if(*arr++ == '0')
{
*arr = '\0';
}
return --arr;
}
// 求余数
long long mod(char *divisor, long long number)
{
long long m=0;
for(int i=0; i<strlen(divisor); i++){
m = (m*10+(divisor[i]-'0'))%number;
}
return m;
}
// 交换
void swap(char *a, char *b, int i)
{
a[i] = a[i]^b[i];
b[i] = a[i]^b[i];
a[i] = a[i]^b[i];
}
python代码import random
def getNum(n):
s = ''
for i in range(n):
s+=str(random.randint(0, 9))
return s
n = 200000
a = getNum(n)
b = getNum(n)
lstA = list(a)
lstB = list(b)
for i in range(n):
if lstA[i] > lstB[i]:
lstA[i], lstB[i] = lstB[i], lstA[i]
newA = int(''.join(lstA))
newB = int(''.join(lstB))
print(newA * newB % 998244353)
|