3 solutions
-
0
跟快速幂的思想差不多: 首先假设a * b mod p;
第一步: 将b进行二进制分解得到(2^0 + 2^1 + 2^3.....) 所以: a * b = a * 2^0 + a *2^1.......; 我们发现后一项是前一项的2倍,因此我们只需要判断b的二进制为是否是1,如果是,就加,不是就不加,然后,得到两个数的乘积后得到一个数,和第三个数继续做上面的操作.
写的不是很清楚
#include <algorithm> using namespace std; const int N = 110; long long ans[N]; int n; long long p; int main() { scanf("%d%ld", &n, &p); for(int i = 1; i <= n; i++) scanf("%lld", &ans[i]); long long res = 0; long long temp = ans[1]; for(int i = 2; i <= n; i++) { long long a = temp; long long b = ans[i]; while(b) { if(b & 1) res = (long long) (res + a) % p; b >>= 1; a = (long long)(a * 2) % p; } if(i != n) { temp = res; res = 0; } } printf("%lld", res); }
Information
- ID
- 1549
- Time
- 1000ms
- Memory
- 256MiB
- Difficulty
- 6
- Tags
- # Submissions
- 146
- Accepted
- 43
- Uploaded By