Nyoj 1197--will you add it? —————— "Fast power, divide and conquer"

Source: Internet
Author: User

Will you add it?  Time limit: Ms | Memory limit: 65535 KB Difficulty: 3
Describe

Give two integers a and N, calculate (A + a^2 + a^3 + ... + a^ (N-1) + a^n)% 666666.

Input
multiple sets of test data.
Each set of data contains two integer a,n (0≤a,n≤10^18).
Output
output (A + a^2 + a^3 + ... + a^ (N-1) + a^n)% 666666 is how much, each group of data occupies one row.
Sample input
2 510 20
Sample output
 62110 



We can always become: when N%2==1, (A1+A2+A3...+AN/2) +an/2* (a1+a2+a3+ ... AN/2) +an.
is (A1+A2+A3...+AN/2) * (an/2+1) +an.
when N%2==0, (A1+A2+A3...+AN/2) +an/2* (a1+a2+a3+ ... AN/2).
is (A1+A2+A3...+AN/2) * (an/2+1). The
can then be divided into solutions.


#include <bits/stdc++.h>using namespace std; #define LL Long Longconst ll mod=666666; ll Pow (ll a,ll x) {  //fast power    ll ret=1;    while (x) {        if (x&1)          ret=ret*a%mod;        A=a*a%mod;        x>>=1;    }    return ret;} ll CALCU (ll a,ll N) {    //Sub    -rule if (n==1)        return A;    LL RET=CALCU (A,N/2);//The return value    ret=ret* (1+pow (A,N/2))%mod of the split part;    if (n%2==1)      //n If an odd number is required plus a^n        ret= (Ret+pow (a,n))%mod;    return ret;} int main () {    LL a,n;    while (scanf ("%lld%lld", &a,&n)!=eof) {        LL ans= calcu (a%mod,n);        printf ("%lld\n", ans);    }    return 0;}

  

Nyoj 1197--will you add it? —————— "Fast power, divide and conquer"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.