I am trying to solve Project Euler+ #97 from Hackerrank. The problem asks to calculate the last 12 digits of A x B ** C + D
. My attempt was to use the modular exponentiation mod 10 ** 12
from Wikipedia in order to efficiently calculate the last 12 digits and avoid overflow. However, for all cases aside from the sample 2 x 3 ** 4 + 5
I am getting wrong. According to the constraints there should be no overflow for unsigned long long
.
The problem:
Now we want to learn how to calculate some last digits of such big numbers. Let's assume we have a lot of numbers A x B ** C + D
and we want to know last 12 digits of these numbers.
Constraints:
- 1 ≤ T ≤ 500000
- 1 ≤ A, B, C, D ≤ 10 ** 9
Input: First line contains one integer T - the number of tests. T lines follow containing 4 integers (A, B, C and D) each.
Output: Output exactly one line containing exactly 12 digits - the last 12 digits of the sum of all results. If the sum is less than 10 ** 12
print corresponding number of leading zeroes then.
My attempt in C
#include <stdio.h>
int main() {
const unsigned long long limit = 1000000000000;
int cases;
for (scanf("%d", &cases); cases; --cases) {
// mult = A, base = B, exp = C, add = D
unsigned long long mult, base, exp, add;
scanf("%llu %llu %llu %llu", &mult, &base, &exp, &add);
base = base % limit;
while (exp) {
if (exp & 1) {
mult = (mult * base) % limit;
}
exp >>= 1;
base = (base * base) % limit;
}
printf("%012llu\n", (mult + add) % limit);
}
return 0;
}