7-1 Multiplication and addition operations of polynomials of one variable (20 points)

Design functions to find the product and sum of two one-variable polynomials respectively.

Input format:
The input is divided into 2 lines. Each line first gives the number of non-zero terms of the polynomial, and then enters the coefficient and exponent of a non-zero term of the polynomial in an exponential descending manner (the absolute values ​​are all integers not exceeding 1000). Separate numbers with spaces.

Output format:
The output is divided into 2 lines, and the coefficients and exponents of the product polynomial and the non-zero terms of the sum polynomial are output in an exponential descending manner. Numbers should be separated by spaces, but there should be no extra spaces at the end. A zero polynomial should output 0 0.

Input example:

4 3 4 -5 2  6 1  -2 0
3 5 20  -7 4  3 1

Output sample:

15 24 -25 22 30 21 -10 20 -21 8 35 6 -33 5 14 4 -15 3 18 2 -6 1
5 20 -4 4 -5 2 9 1 -2 0
#include<stdio.h>
int main()
{
    
    
	int i,j,k=0,
		mul[20000]={
    
    0},add[20000]={
    
    0},
		c1[1000]={
    
    0},x1[1000]={
    
    0},
		c2[1000]={
    
    0},x2[1000]={
    
    0},
		c=0,x=0,
        n1=0,n2=0;

	scanf("%d",&n1);
	for(i=0; i<n1; i++){
    
    
		scanf("%d %d",&c1[i],&x1[i]); //c1存系数,x1存指数
		add[x1[i]] = add[x1[i]] + c1[i];//加法运算结果中系数;
	}

	scanf("%d",&n2);
	for(i=0; i<n2; i++){
    
    
		scanf("%d %d",&c2[i],&x2[i]);
		add[x2[i]] = add[x2[i]] + c2[i];///用来储存加法运算结果中的系数;
	}

	for(i=0; i<n1; i++){
    
    
		for(j=0; j<n2; j++){
    
    
			c = c1[i] * c2[j];
			x = x1[i] + x2[j];//指数下标
			mul[x] = mul[x] + c;//系数;
		}
	}
	//输出多项式的积 
	for(i=2000,k=0; i>=0; i--){
    
    
		if(mul[i] != 0){
    
    
			c1[k] = mul[i];//系数 
			x1[k] = i;//指数 
			k++;
		}//if
	}//for
	for(i=0; i<k; i++){
    
    
		printf("%d %d",c1[i],x1[i]);
		if(i<k-1) printf(" ");
	}
	if(k==0) printf("0 0");
	printf("\n");

	//输出多项式的和 
	for(i=1000,k=0; i>=0; i--){
    
    
		if(add[i] != 0){
    
    
			c2[k] = add[i];
			x2[k] = i;
			k++;
		}//if
	}//for
	for(i=0; i<k; i++){
    
    
		printf("%d %d",c2[i],x2[i]);
		if(i<k-1) printf(" ");
	}//for
	if(k==0) printf("0 0");
	return 0;
}

Guess you like

Origin blog.csdn.net/YSA_SFPSDPGY/article/details/114851528