日期:2025年7月12日
ZeroJudge 題目連結:a248. 新手訓練 ~ 陣列應用
解題想法
理論上這題是要先計算 a, b 相除的商,接著再取 a %= b,每次將 a 乘以 10 倍之後除以 b,計算小數的部分直到 n 位數為止,但是這個作法在 Python 會太慢。反而可以利用 Python 支援大數運算的特性,直接將 a%b 乘以 $10^n$ 再除以 b 計算小數的部分,但是要記得在小數部分前面補 0 到 n 位數。
Python 程式碼
寫法1,超時。
import sys
result = []
lines = sys.stdin.readlines()
for line in lines:
if not line.rstrip(): continue
a, b, n = map(int, line.split())
int_part = a//b
a %= b
res = [f"{int_part:d}."]
for _ in range(n):
a *= 10
c = a//b
res.append(f"{c:d}")
a %= b
result.append("".join(res) + "\n")
sys.stdout.write("".join(result))
寫法2,大數運算,使用時間約為 0.5 s,記憶體約為 17.2 MB,通過測試。
import sys
result = []
lines = sys.stdin.readlines()
for line in lines:
if not line.rstrip(): continue
a, b, n = map(int, line.split())
int_part = a//b
dec_part = str(a%b*(10**n) // b).zfill(n)
result.append(f"{int_part:d}.{dec_part}\n")
sys.stdout.write("".join(result))
C++ 程式碼
使用時間約為 0.6 s,記憶體約為 80 kB,通過測試。
#include <cstdio>
using namespace std;
int main() {
int a, b, n;
while(scanf("%d %d %d", &a, &b, &n) != EOF) {
printf("%d.", a/b);
a %= b;
for(int i=0; i<n; i++) {
a *= 10;
printf("%d", a/b);
a %= b;
}
puts("");
}
return 0;
}
沒有留言:
張貼留言