<OJ_Sicily>Polynomial

本文介绍了一种基于数组实现的大整数多项式求值算法,适用于系数和变量值较大的情况。该算法通过逐项累加权重值并处理进位,最终得出多项式的计算结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

 Given a polynomial and the value of the variable x, you task is to calculate the value of the polynomial.

Input

The first line of the input is a positive integer T. T is the number of test cases followed.

In each test case, the first line contains two integer n and x (0<=n<=50, 0<=x<=10000). The second line contains n+1 integers, representing the coefficients of a polynomial from power degree N down to power degree 0, each integer is no less than 0 and no more than 10000.

Output

The output of each test case should consist one line, containing the result of the polynomial.

题目解释:求解多项式的值。多项式包括一个基数,还有n个权重。在这里输入基数为x,还有n个权重值a1,a2,a3。。。则有:

a1*xn + a2*xn-1 + a3*xn-2 +…+ an*x0

可以化解成:

= (…(((x+a1)*n+a2)*n+a3)+…)


因此可以参考这个思路来求解。由于这涉及到大整数,是因为结果的长度会超出基本类型的范围,在这里使用数组记录长整数。

(1)初始化一个数组 result[201]

(2)对于数组的每一位都乘以基数x,乘完后进行进位处理

(3)对于数组的最低位进行加权值操作。

#include <iostream>
#include <string.h>
#define MAX_LEN 201
using namespace std;
int result[MAX_LEN];
int main(){
    int T;
    cin >> T;
    while (T > 0) {
        int n, x;
        cin >> n >> x;
        memset(result, 0, sizeof(result));
        for (int i = 0; i <= n; i++) {
            int carray = 0;
            for (int j = MAX_LEN - 1; j >= 0; j--) {   // 对于数组每一个数都乘以x
                result[j] = result[j] * x + carray;
                carray = result[j] / 10;
                result[j] = result[j] % 10;
            }
            int q;
            cin >> q;
            carray = q;
            for (int j = MAX_LEN - 1; j >=0 ; j--) {   // 对于数组最低位进行加权值操作
                result[j] = result[j] + carray;
                carray = result[j] / 10;
                result[j] = result[j] % 10;
            }
        }
        bool flag = false;
        for (int i = 0; i < MAX_LEN; i++) {
            if (result[i] != 0) {   // 遇到了第一个不为0 的数
                flag = true;
            }
            if (flag) cout << result[i];
        }
        cout << endl;
        T--;
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值