Fast Power modulo---> (a^b)%c

Source: Internet
Author: User




First you need to know a formula a*b%c= ((a%c) *b)%c, and then you can try to write an inefficient algorithm based on this formula.


/*     (a*a*a*...*a)%c  = ((a*a*). *a)%c*a)%c  = ((*.. *a)%c*a)%c*a)%c = (((((((a%c*a)%c...*a)%c*a)%c*a)%c*a  #include%c*/<stdio.h>int (int qmod a,int c) {    //According to the introduction of the formula, easy to know    int sum=a%c;    b=b-1;    while (b--)    {        sum=sum*a%c;    }    For more aesthetic simplicity, it can be written as    int sum=1;//a*1=a    while (b--)    {        sum=sum*a%c;    }    return sum;} int main () {//a*b%c== ((a%c) *b)%c  int a,b,c;  while (scanf ("%d%d%d", &a,&b,&c)!=eof)  {      printf ("%d\n", Qmod (A,b,c));}  }

The next step is to raise the efficiency of the problem, how to improve efficiency?


This formula A^b%c, which has been optimized for mod modulo

The key now is to optimize the a^b.


These two simple formulas need to be remembered: 1): a^b= (a^2) ^ (B/2)-->b for even 2): a^b= (a^2) ^ (B/2) *a-->b for Odd


#include <stdio.h>int qmod (int a,int b,int c) {    int sum=1;    while (b)    {        if (b&1)          sum=sum*a%c;//multiply by one A;        a=a*a%c;        b>>=1;    }    return sum;} int main () {//a*b%c== ((a%c) *b)%c  int a,b,c;  while (scanf ("%d%d%d", &a,&b,&c)!=eof)  {      printf ("%d\n", Qmod (A,b,c));}  }



Attached: 1): YY right Shift x represents yy divided by 2^x 2):yy left Shift x represents yy multiplied by 2^x



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Fast Power modulo---> (a^b)%c

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.