日期:2026年5月3日
ZeroJudge 題目連結:d219. 00374 - Big Mod
解題想法
這題的題目敘述有問題,實際上要求的是 $$ R = B^P \pmod M $$ 這題的範例測資是 b、p、m 分成 3 行,但實際的測資是 3 個數在同一行並用空格分隔,用 Python 解題的話建議用 data = sys.stdin.read().split() 一次讀取所有測資並分割,再用索引值從 data 讀取資料會比較方便。 這題想要考快速冪,並在計算次方時取模。由於 Python 的 pow 內建這樣的功能,可以直接使用,語法為
pow(底數, 次方, 模數)
如果用 C++ 解題的話要自己寫。
Python 程式碼
使用時間約為 37 ms,記憶體約為 11.1 MB,通過測試。
def solve():
import sys
result = []
data = sys.stdin.read().split()
ptr = 0
while ptr < len(data):
b = int(data[ptr])
p = int(data[ptr+1])
m = int(data[ptr+2])
ptr += 3
result.append(f"{pow(b, p, m):d}\n")
sys.stdout.write("".join(result))
if __name__ == "__main__":
solve()
C++ 程式碼
使用時間約為 3 ms,記憶體約為 1.5 MB,通過測試。
#include <cstdio>
typedef long long LL;
LL myexp(LL b, LL p, LL m) {
LL r = 1;
while(p > 0) {
if (p&1) {
r = (r * b) % m;
}
b = (b * b) % m;
p >>= 1;
}
return r;
}
int main() {
LL b, p, m;
while(scanf("%lld %lld %lld", &b, &p, &m) != EOF) {
printf("%lld\n", myexp(b, p, m));
}
return 0;
}
沒有留言:
張貼留言