a862中等

113 嘉義資訊程式競賽|長實數相乘後轉為二進位

精確轉換乘積的二進位小數。

解題思路

每個十進位字串移掉小數點,得到整數A與小數位數a,原數恰為A/10^a。兩數乘積就是AB/10^(a+b),全程不使用浮點。

先計算Q=floor(AB×1024/10^(a+b)),這恰是乘積保留10個二進位小數位後的定點整數。整數部分是Q>>10,小數10位是Q的最低10位。

以大整數重複除2或位移輸出整數部分,若為0仍印0;小數部分必補滿10位。正數向下取整正好符合直接捨去。

D為輸入總位數,使用大整數乘除成本(樸素上界O(D²)),O(D)儲存空間。

Step-by-step animation

示例:移點後為15×25/100=375/100。

回報動畫錯誤
步驟 1 / 3

1.5×2.5

移點後為15×25/100=375/100。

A15
B25
分母100
乘積
3.75

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::cpp_int;
int main() {
    string a, b;
    cin >> a >> b;
    auto parse = [](string s) {
        cpp_int x = 0;
        int scale = 0;
        bool dot = 0;
        for (char c : s)
            if (c == '.')
                dot = 1;
            else {
                x = x * 10 + (c - '0');
                if (dot)
                    scale++;
            }
        return pair<cpp_int, int>{x, scale};
    };
    auto [A, x] = parse(a);
    auto [B, y] = parse(b);
    cpp_int den = 1;
    for (int i = 0; i < x + y; i++)
        den *= 10;
    cpp_int q = A * B * 1024 / den, integer = q >> 10;
    int frac = (q & 1023).convert_to<int>();
    string s;
    if (integer == 0)
        s = "0";
    while (integer > 0) {
        s.push_back((integer & 1) != 0 ? '1' : '0');
        integer >>= 1;
    }
    reverse(s.begin(), s.end());
    cout << s << '.';
    for (int i = 9; i >= 0; i--)
        cout << ((frac >> i) & 1);
    cout << '\n';
}

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

更多