其他分享
首页 > 其他分享> > 大数乘除 长整数的处理

大数乘除 长整数的处理

作者:互联网


假定用一个整型数组表示一个长整数,数组的每个元素存储长整数的一位数字,则实际的长整数m表示为:
m=a[k]*10^k-1+a[k-1]*10^k-2+...+a[2]*10+a[1]

a[0]保存该长整数的位数。求:
(1)长整数乘普通整数;(2)长整数除普通整数
 

#include<stdio.h>
int c[1000] = { 0 }, di[1000] = { 0 };
int remain = 0;
void get(int d[])
{
	int i, temp;
	for (i = 1;; ++i)
	{
		d[i] = getchar() - 48;
		if (d[i] == -38 || d[i] == -16)
			break;
	}
	d[0] = i - 1;
	d[i] = 0;
	for (i = 1; i <= d[0] / 2; ++i)
	{
		temp = d[i];
		d[i] = d[d[0] - i + 1];
		d[d[0] - i + 1] = temp;
	}
}

void multiply(int x[], int y[])
{
	int ca = 0;
	int re = 0;
	c[0] = x[0] + y[0];
	for(int i = 1; i <= y[0]; i++)
		for (int j = 1; j <= x[0]; j++)
		{
			int temp = y[i] * x[j] + c[i + j ];
			ca = temp / 10;
			re = temp % 10;
			c[i + j + 1] += ca;
			c[i + j] = re;
		}
	if (c[c[0]] == 0)
		c[0] -= 1;
}
void div(int x[], int y)
{
	int i, j, b =0;
	int k[1000] = { 0 };
	for ( i = x[0]; i >= 1; i--)
	{
		
		b = b * 10 + x[i];
		k[i] = b / y;
		b = b % y;
	}
	i = x[0];
	j = 1;
	while (k[i] == 0)
		i--;
	for (; i >=1; i--)
		di[j++] = k[i];
	di[0] = j;
	remain = b;
}
void main()
{


		int a[1000] = { 0 }, b[1000] = { 0 };
		int n;
		int choose;
		printf("1为乘法,2为除法\n");
		scanf_s("%d", &choose);
		switch (choose)
		{
		case 1:
			getchar();
			printf("请输入一个长整数:\n");
			get(a);
			printf("请输入一个普通整数:\n");
			get(b);
			multiply(a, b);
			printf("相乘的结果是:\n");
			for (int i = c[0]; i > 1; i--)
			{
				printf("%d", c[i]);

			}
			printf("\n----------------\n\n");
			break;
		case 2:
			getchar();
			printf("请输入一个长整数:\n");
			get(a);
			printf("请输入一个普通整数:\n");
			scanf_s("%d", &n);
			div(a, n);
			printf("相除的结果是:\n");
			for(int i = 1; i < di[0]; i++ )
			{
				printf("%d", di[i]);
			
			}
			printf("\n余数是:\n %d", remain);
			printf("\n----------------\n\n");
			break;
		default:
			break;
		}

		system("pause");
}

 

标签:di,int,大数,整数,break,乘除,printf,get
来源: https://blog.csdn.net/qq_42722002/article/details/90758570