uva 10719 Quotient Polynomial(多项式相除)

A polynomial of degree n can be expressed as

If k is any integer then we can write:

Here q(x) is called the quotient polynomial of p(x) of degree (n-1) and r is any integer which is called the remainder.

For example, if p(x) = x- 7x2+ 15x - 8 and k = 3 then q(x) = x- 4x + 3 and r = 1. Again if p(x) = x- 7x2+ 15x - 9 and k = 3 thenq(x) = x- 4x + 3 and r = 0.

In this problem you have to find the quotient polynomial q(x) and the remainder rAll the input and output data will fit in 32-bit signed integer.

Input
Your program should accept an even number of lines of text. Each pair of line will represent one test case. The first line will contain an integer value for k. The second line will contain a list of integers (an, an-1, … a0), which represent the set of co-efficient of a polynomial p(x). Here 1 ≤ n ≤ 10000. Input is terminated by <EOF>.

Output
For each pair of lines, your program should print exactly two lines. The first line should contain the coefficients of the quotient polynomial. Print the reminder in second line. There is a blank space before and after the ‘=’ sign. Print a blank line after the output of each test case. For exact format, follow the given sample.

Sample Input

Output for Sample Input

3
1 –7 15 –8
3
1 –7 15 –9

q(x): 1 -4 3
r = 1

q(x): 1 -4 3
r = 0


题目大意:多项式求除法商,就是将多项式分解成p(x) = (x - k) * q(x), 求q(x)各项的系数.

解题思路:q(x)中除了最高次项的系数与p(x)最高项的系数相同,其它系数有一个规律q[i] = p[i] + k * q[i - 1].

#include<stdio.h>
#include<string.h>
#define N 10005
int main(){
	int k, n, p[N], q[N];
	while (scanf("%d", &k) != EOF){
		// Init.
		memset(p, 0, sizeof(p));
		memset(q, 0, sizeof(q));
		char c = '\0';
		n = 0;

		while (1){
			scanf("%d%c", &p[n++], &c);
			if (c == '\n')
				break;
		}

		q[0] = p[0];
		for (int i = 1; i < n; i++)
			q[i] = p[i] + k * q[i - 1];
		
		// Printf.
		printf("q(x):");
		for (int i = 0; i < n - 1; i++)
			printf(" %d", q[i]);
		printf("\nr = %d\n", q[n - 1]);
		printf("\n");
	}
	return 0;}

你可能感兴趣的:(uva 10719 Quotient Polynomial(多项式相除))