a693中等移除小數點後的精確大數乘方

CPE:Exponentiation (UVa 748)

以整數乘冪和小數位數還原精確十進位輸出。

前往題目練習 →回報教學錯誤A有B位、結果最多D位;此小整數乘法時間 O(nD),空間 O(D),n≤25。

解題思路

把 R 視為十進位字串,移除小數點得到整數 A,原本小數位數為 d,則 Rⁿ=Aⁿ/10^(dn)。計算時不使用浮點數:Python直接求整數冪,C++以十進位字串反覆乘小整數A,逐位維護進位。

若整數結果位數不大於 dn,先在左側補零,確保能在倒數 dn 位插入小數點。只刪除小數部分的尾零,再刪不必要的小數點,最後省略小於1時的整數0;整數部分的尾零不可刪。讀到EOF,輸出完整數字,不可科學記號。R>0,所以不會遇到零的空字串問題,程式仍保留0的防護。

Step-by-step animation

示意:R=0.50,n=3

回報動畫錯誤
步驟 1 / 3

縮放

移除小數點,A=50,d=2。

0.50
A=50
d=2
總小數位
6

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string multiply(string s, int factor) {
    string out;
    long long carry = 0;
    for (int i = (int)s.size() - 1; i >= 0; i--) {
        long long v = (s[i] - '0') * 1LL * factor + carry;
        out += char('0' + v % 10);
        carry = v / 10;
    }
    while (carry) {
        out += char('0' + carry % 10);
        carry /= 10;
    }
    reverse(out.begin(), out.end());
    return out;
}
int main() {
    string r;
    int n;
    while (cin >> r >> n) {
        auto point = r.find('.');
        int digits = point == string::npos ? 0 : (int)r.size() - (int)point - 1;
        if (point != string::npos)
            r.erase(point, 1);
        int base = stoi(r), scale = digits * n;
        string answer = "1";
        for (int i = 0; i < n; i++)
            answer = multiply(answer, base);
        if (scale) {
            if ((int)answer.size() <= scale)
                answer = string(scale + 1 - answer.size(), '0') + answer;
            answer.insert(answer.size() - scale, 1, '.');
            while (answer.back() == '0')
                answer.pop_back();
            if (answer.back() == '.')
                answer.pop_back();
        }
        while (answer.size() > 1 && answer[0] == '0')
            answer.erase(0, 1);
        cout << answer << '\n';
    }
}

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

更多