Raising modulo numbers (zoj 2150)

Source: Internet
Author: User

This is the answer to the question.

#include<iostream>#include<cmath>using namespace std;int a[45002];int b[45002];int mod(int a, int b, int c){    int z = 1;    while(b)    {        if(b%2)            z = (z*a)%c;        b/=2;        a = (a*a)%c;    }    return z;}int main(){    int T;    cin>>T;    while(T--)    {        int M;        int H;        cin>>M>>H;        for(int i=0; i<H; i++)        {            cin>>a[i]>>b[i];        }        int t =0;        int mode = 0;        while(t<H)        {            int tem0 = a[t]%M;            mode = (mod(tem0,b[t],M) + mode)%M;            t++;        }        cout<<mode<<endl;    }}
View code

Analyze only the function for power-modulo. Let's take an example (a A a). This is B a (B = 10 ), use Z to record the generated by two-point division. Use a to replace a * A after each Binary Division. This results in a scale-down. Finally, it must be B = 1, so now we only need to use the combination of a and Z to get the final result.

int mod(int a, int b, int c){    int z = 1;    while(b)    {        if(b%2)            z = (z*a)%c;        b/=2;        a = (a*a)%c;    }    return z;}

This function is just written in a binary method, but I wrote it in the beginning.

long long F(long long a, long long b, long long m){    if(b==1)        return a%m;    else if(b%2==0)        return (F(a,b/2,m)*F(a,b/2,m))%m;    else        return (F(a,b/2,m)*F(a,b/2,m)*a%m);}

The result of this write is re. It is estimated that the recursion is too deep, leading to stack overflow. This write is very poor and does not have a binary effect at all. Instead, it takes more time than O (n.

Raising modulo numbers (zoj 2150)

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.