gpt4 book ai didi

c - 将两个数字 [1, 10^10000] 作为字符数组相加 - C

转载 作者:行者123 更新时间:2023-11-30 20:33:37 25 4
gpt4 key购买 nike

我通过首先计算出两个给定数字的长度并将数字较少的数字(如果存在)对齐到一个新数组中来解决这个问题,以便个位、十位、百位等与较大数字的数字对齐,数十、数百等然后我想将每两个对齐元素的总和(模为 10)保存到一个新数组中,同时检查数字总和是否大于 10 - 只是基本的总和内容。现在,在 aplusb 整数中添加两个元素时出现问题,我尝试通过编写

来修复它
int aplusb = (lengthA[max-i]-'0') +(temp[max-i]-'0');

但它不起作用。我被困住了,我不知道该怎么办。请帮忙。

整个代码:

#include <stdio.h>
#include <math.h>

int main(){
char a[10000];
char b[10000];
scanf("%s %s", &a, &b);
char sum[10000];
int lengthA = 0;
int lengthB = 0;

int i = 0;
while(a[i]){
i++;
} lengthA = i;

i = 0;
while(b[i]){
i++;
} lengthB = i;
char temp[10000];

int aplusb;
int carry = 0;

int max = lengthA;
int difference = abs(lengthA - lengthB);
if(lengthA>lengthB){
for(i=0; i<lengthA; i++){
temp[i+difference]=b[i];
}
for(i=0; i<=max; i++){
aplusb = lengthA[max-i]+temp[max-i]; //<-- this is the problematic line
if(carry = 1) aplusb++;
if(aplusb>9){
carry = 1;
aplusb%=10;
}
sum[i]=aplusb;
}
}

for(i=0; i<=max; i++){
printf("%c", sum[i]);
}

/*
if(lengthB>lengthA){
max = lengthB;
for(i=0; i<lengthB; i++){
temp[i+difference]=a[i];
}
}*/

return 0;
}

最佳答案

对非常大的数字进行运算和存储与进行运算和存储多项式非常相似,即 x = 10.a0 + a1.10 + a2.10^2 ... + an.10^n。

互联网上有许多多项式库,您可以在其中找到灵感。对非常大的数字的所有运算都可以用多项式表示。这意味着通过使用基数 2^8,甚至基数 2^63,而不是基数 10 来内部存储大数字,您将大大提高性能。

您还必须在运算后对系数进行归一化,以使其保持正值。运算可能会产生负系数,这很容易修复,因为它与减法后的借位非常相似,这意味着系数必须比基数大 1 位。

要转换回基数 10,您需要通过 r(您的结果)求解 v(您的值),例如 r(10)=v(2^63)。如果您强制执行正系数规则,则只有一种解决方案。

[注]再想一想:毕竟,正系数的规则可能只在打印时才需要。

示例:添加。 没有内存错误检查

int addPolys(signed char** result, int na, const signed char* a, int nb, const signed char* b)
{
int i, nr, nmin, carry, *r;

nr = max(na, nb) + 1;
nmin = min(na, nb);

r = malloc(sizeof(signed char) * (na + nb + 1));

if (nb < na)
{
nr = nb;
}

for (i = 0; i < nmin; ++i)
{
r[i] = a[i] + b[i];
}
for (; i < na; ++i)
{
r[i] = a[i];
}
for (; i < nb; ++i)
{
r[i] = b[i];
}
r[nr - 1] = 0;
// carry - should really be a proc of its own, unoptimized
carry = 0;
for (i = 0; i < nr; ++i)
{
r[i] += carry;
if (r[i] > 10)
{
carry = r[i] / 10;
r[i] %= 10;
}
else if (r[i] < 0)
{
carry = (r[i] / 10) - 1;
r[i] -= (carry * 10);
}
else
carry = 0;
}

// 'remove' leading zeroes
for (i = nr - 1; i > 0; --i)
{
if (r[i] != 0) break;
}
++i;

*result = r;
if (i != nr)
{
*result = realloc(i * sizeof(signed char));
}
return i; // return number of digits (0 being 1 digit long)
}

关于c - 将两个数字 [1, 10^10000] 作为字符数组相加 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44630266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com