Example of C + + fast power and large number modulo algorithm _c language

Source: Internet
Author: User

One, fast power

In fact (a^b)% p , is to ask, (which a,b,p are larger in the range of int) such problems.

First you know the formula for the remainder: (a*b)%p=(a%p*b%p)%p .

So the power is not the accumulation of opportunity, which gives the code:

int fast (int a,int b,int p)

{  long long a1=a,t=1;

  while (b>0)  

  {if (b&1)     /If power B is odd multiply once, because there will be 2 variable even number, (7/2=3)

  t= (t%p) * (a1%p)%p;

  a1= (a1%p) * (a1%p)%p; 

  b/=2;  }

 return (int) (t%p);

}

Two, the large number takes the model

The principle is that the remainder formula:(a+b)%p=(a%p+b%p)%p;

The large number can be seen as each digit multiplied by its own weight and then added to each digit.

such as: 12345678 = (1*10000000) + (2*1000000) +...+8.

The code is as follows:

Char s[200];

#define MOD 10000010;

int main ()

{  while (gets (s))

{  int k=strlen (s), sum=0;

 for (int i=0;i<k;i++)

 sum= (sum*10+s[i]-' 0 ')%mod;  /Of course, if you are worried that sum may overflow, then open the inside again to remove the

 cout<<sum<<endl;

}}

Third, summary

The above is the entire content of this article, I hope for everyone's study and work can help. If you have questions, you can exchange messages.

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.