b298中等

88 雲嘉區資訊學科能力競賽|級數計算

以程式計算101項指定級數至四位小數。

解題思路

以程式計算101項指定級數至四位小數。

第一項為1,接下來100項依序為1/(2i),i=1至100。不是每次把前項分母加倍。

以有理數逐項加總,分母與分子以最大公因數約分,得到唯一精確總和。

最後將總和乘10000並half-up取整,再格式化四位小數;教學範例為自製,原題沒有公開完整輸出卡。

固定101項,算術操作次數O(1),有理數位數為固定常數;無輸入。

Step-by-step animation

固定級數的精確有理數累加逐步追蹤

回報動畫錯誤
步驟 1 / 3

步驟 1

先累加第一項1。

sum=1
步驟
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using boost::multiprecision::cpp_int;
using ll = long long;
#include <boost/rational.hpp>
using Q = boost::rational<cpp_int>;
Q rat(cpp_int a, cpp_int b) {
    if (b < 0) {
        a = -a;
        b = -b;
    }
    return Q(a, b);
}
cpp_int abig(cpp_int a) {
    return a < 0 ? -a : a;
}
cpp_int ten(int n) {
    cpp_int a = 1;
    while (n--)
        a *= 10;
    return a;
}
Q dec(string s) {
    auto slash = s.find('/');
    if (slash != string::npos)
        return Q(cpp_int(s.substr(0, slash)), cpp_int(s.substr(slash + 1)));
    bool neg = !s.empty() && s[0] == '-';
    if (s[0] == '-' || s[0] == '+')
        s.erase(s.begin());
    auto p = s.find('.');
    int k = p == string::npos ? 0 : s.size() - p - 1;
    if (p != string::npos)
        s.erase(p, 1);
    size_t z = s.find_first_not_of('0');
    cpp_int a = z == string::npos ? cpp_int(0) : cpp_int(s.substr(z));
    return Q(neg ? -a : a, ten(k));
}
string fixedq(Q q, int digits) {
    cpp_int a = q.numerator(), b = q.denominator(), scale = ten(digits);
    bool neg = a < 0;
    a = abig(a);
    cpp_int k = (2 * a * scale + b) / (2 * b);
    string s = k.convert_to<string>();
    if (digits) {
        if (s.size() <= digits)
            s = string(digits + 1 - s.size(), '0') + s;
        s.insert(s.size() - digits, ".");
    }
    return (neg && k != 0 ? "-" : "") + s;
}
string finiteq(Q q) {
    cpp_int a = q.numerator(), b = q.denominator();
    bool neg = a < 0;
    a = abig(a);
    cpp_int whole = a / b, r = a % b;
    string s = whole.convert_to<string>();
    if (r != 0) {
        s += '.';
        while (r != 0) {
            r *= 10;
            cpp_int z = r / b;
            s += char('0' + z.convert_to<int>());
            r %= b;
        }
    }
    return (neg ? "-" : "") + s;
}
int main() {
    Q sum(1);
    for (int i = 1; i <= 100; i++)
        sum += Q(1, 2 * i);
    cout << fixedq(sum, 4) << '\n';
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多