C语言实现大数加减乘除代码
时间: 2023-03-15 16:41:35 浏览: 235
RSA C++实现,用C++描述的算法,可以清楚地了解,大数的加减乘除算法
4星 · 用户满意度95%
C语言实现大数加减乘除的代码如下://定义大数结构体
typedef struct
{
int data[1000];
int length;
} bignum;//定义计算函数
void calculate(bignum *num1, bignum *num2, char ope)
{
if (ope == '+')
{
int temp = 0;
int i;
for (i = 0; i < num1->length || i < num2->length; i++)
{
temp += num1->data[i] + num2->data[i];
num1->data[i] = temp % 10;
temp /= 10;
}
num1->length = i;
if (temp != 0)
{
num1->data[i] = temp;
num1->length++;
}
}
else if (ope == '-')
{
int temp = 0;
int i;
for (i = 0; i < num1->length; i++)
{
temp += num1->data[i] - num2->data[i];
if (temp < 0)
{
num1->data[i] = temp + 10;
temp = -1;
}
else
{
num1->data[i] = temp;
temp = 0;
}
}
num1->length = i;
if (temp != 0)
{
num1->data[i] = temp;
num1->length++;
}
}
else if (ope == '*')
{
int temp = 0;
int i;
for (i = 0; i < num1->length + num2->length; i++)
{
int j;
for (j = 0; j <= i; j++)
{
temp += num1->data[j] * num2->data[i - j];
}
num1->data[i] = temp % 10;
temp /= 10;
}
num1->length = i;
if (temp != 0)
{
num1->data[i] = temp;
num1->length++;
}
}
else if (ope == '/')
{
bignum temp;
int i;
for (i = 0; i < num2->length; i++)
{
temp.data[i] = num1->data[i];
}
temp.length = num2->length;
int j = 0;
for (i = num2->length; i < num1->length; i++)
{
temp.data[temp.length++] = num1->data[i];
while (cmp(&temp, num2) >= 0)
{
sub(&temp, num2);
num1->data[j++]++;
}
}
num1->length = j;
}
}
阅读全文