a587中等導數係數的Horner法
CPE:498-bis (UVa 10268)
不計算冪次,線性累積多項式導數值。
解題思路
若原係數依最高次到常數排列為a₀..aₙ,導數係數就是na₀、(n−1)a₁、…、aₙ₋₁。常數項消失,所以只處理前n個係數;只有一個係數時n=0,結果為0。
用Horner法從高次到低次,反覆令answer=answer×x+(n−i)aᵢ。處理到i時,answer等於已處理導數係數構成的前綴多項式在x的值,下一次乘x就把既有項提升一階。每筆係數個數由整行決定,不能跨行讀到下一筆x;讀至EOF。
本地敘述未限制多項式次數,只保證最後答案在有號32位元內。Python整數可直接算;C++改在模2³²下做相同的加乘,使用uint32_t使溢位有明確定義,最後將最高位為1的結果減2³²還原負數。因真實答案已保證落在此範圍,模數結果能唯一還原,不必假設中間值也放得進64位元。
Step-by-step animation
示意:P(x)=2x³−3x²+4x+5,在x=2求導數
步驟 1 / 3
首係數
導數為6x²−6x+4,先處理6。
原2,-3,4,5
導6,-6,4
- answer
- 6
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <iomanip>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <tuple>
#include <functional>
#include <limits>
#include <cstdint>
#include <cctype>
#include <utility>
using namespace std;
int main() {
long long x;
string line;
while (cin >> x) {
getline(cin, line);
if (!getline(cin, line))
break;
istringstream in(line);
vector<long long> a;
long long value;
while (in >> value)
a.push_back(value);
int n = int(a.size()) - 1;
// All arithmetic is modulo 2^32; unsigned overflow is defined.
uint32_t answer = 0, base = static_cast<uint32_t>(x);
for (int i = 0; i < n; ++i)
answer = answer * base + static_cast<uint32_t>(n - i) * static_cast<uint32_t>(a[i]);
long long signedAnswer = answer;
if (answer >= 0x80000000u)
signedAnswer -= 4294967296LL;
cout << signedAnswer << '\n';
}
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。