Method
multiply
(long a, long b, long mod)
Source from the content-addressed store, hash-verified
| 64 | // 讲解033 - 位运算实现乘法 |
| 65 | // a*b过程每一步都%mod,这么写是防止溢出,也叫龟速乘 |
| 66 | public static long multiply(long a, long b, long mod) { |
| 67 | a = (a % mod + mod) % mod; |
| 68 | b = (b % mod + mod) % mod; |
| 69 | long ans = 0; |
| 70 | while (b != 0) { |
| 71 | if ((b & 1) != 0) { |
| 72 | ans = (ans + a) % mod; |
| 73 | } |
| 74 | a = (a + a) % mod; |
| 75 | b >>= 1; |
| 76 | } |
| 77 | return ans; |
| 78 | } |
| 79 | |
| 80 | public static void main(String[] args) throws IOException { |
| 81 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
Tested by
no test coverage detected