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