CH0102 64 位整数乘法
Description
求 a 乘 b 对 p 取模的值,其中
Input
第一行 a,第二行 b,第三行 p。
Output
一个整数,表示
Sample Input
1 | 2 |
Sample Output
1 | 6 |
Limit
| Time Limit | Memory Limit |
|---|---|
| C/C++/Rust/Pascal 1 秒,其他语言 2 秒 | C/C++/Rust/Pascal 32 M,其他语言 64 M |
Analysis
由于
回到对乘法的理解:
显然我们可以通过多步加法来实现乘法。但是
Algorithm
直接计算long long 的范围。把乘数
则:
因此不必把t 表示当前的res 累加已经处理的位所对应的贡献:
- 若当前最低位是
( b & 1),就把t加入res。 - 将
t加倍,得到下一位对应的。 - 将
b右移一位,继续处理下一位。
例如
1 |
|
算法时间复杂度为
,额外空间复杂度为 。
Template
1 | template <class T> |
Ref
- Title: CH0102 64 位整数乘法
- Author: Neurocoda
- Created at : 2026-09-26 16:29:30
- Updated at : 2026-09-26 16:54:18
- Link: https://neurocoda.com/p/287a3963.html
- License: This work is licensed under CC BY-ND 4.0.
Recommend