[Sum] LuoguP1630

Description

[Sum] LuoguP1630

Given $ a, b $, seeking $ (\ sum \ limits_ {i = 1} ^ {a} {i ^ b}) \ mod 10000 $

Multiple sets of inquiries, $ a, b \ le 1e9 $

Solution

Fast and power prefix +

If violence calculate the answer, then the time complexity is $ O (Tab) $

Use fast power optimization, the time complexity is $ O (Ta \ log b) $

Consider a formula: $$ i ^ b \ mod n = (i \ mod n) ^ b $$

Then we can preprocessing the $ i ^ b, i \ in [0,9999] $ value, the time complexity becomes $ O (Ta) $

Consider each $ i ^ b \ mod value of $ 10,000, the entire sequence is found in $ i ^ b, i \ in [0,9999] $ repeated $ \ lfloor \ frac {a} {10000} \ rfloor $ times, coupled with the last remaining $ i ^ b, i \ in [0,9999] $ before $ a \ mod 10000 $ number

Then we can handle the $ i ^ b \ mod prefix and $ 10,000, then after the pretreatment $ O (1) $ to complete

In this way it becomes a time complexity $ O (T \ times 10000 \ times \ log b) $

Code

#include <bits/stdc++.h>
// check if it is judged online

namespace shl {
    typedef long long ll;
    inline ll read() {
        ll ret = 0, op = 1;
        char c = getchar();
        while (!isdigit(c)) {
            if (c == '-') op = -1;
            c = getchar();
        }
        while (isdigit(c)) {
            ret = ret * 10 + c - '0';
            c = getchar();
        }
        return ret * op;
    }
    int T;
    int a, b;
    ll c[10010], sum[10010];
    const int mod = 1e4;
    ll qpow(ll x, ll y) {
        ll ret = 1;
        while (y) {
            if (y & 1) ret = (ret * x) % mod;
            x = x * x % mod;
            y >>= 1;
        }
        return ret;
    }
    int main() {
        T = read();
        while (T--) {
            a = read(), b = read();
            for (register int i = 0; i < 10000; ++i) {
                c[i] = qpow(i, b);
                if (i == 0) sum[i] = c[i];
                else sum[i] = sum[i - 1] + c[i];
            }
            printf("%lld\n", ((sum[mod - 1] * (a / mod) % mod) + sum[a % mod]) % mod);
        }
        return 0;
    }
}
int main() {
#ifdef LOCAL
    freopen("textname.in", "r", stdin);
    freopen("textname.out", "w", stdout);
#endif
    shl::main();
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/shl-blog/p/11574307.html
sum