快速幂算法及注意事项

来源:互联网 发布:手机怎么拍淘宝图片 编辑:程序博客网 时间:2024/04/30 13:32

快速幂

题目:设有x,y两整数,快速求x^y.

思想:降低指数,提高底数。

分析:若指数为偶数则指数除以二,底数变成原来的平方;

            若指数为奇数则在记录最终答案的变量中乘一个底数,指数整除以二,底数仍变为原来的平方。

程序:

program g;var n,l:longint;     ans,x,y:qword;begin read(n); for l:=1 to n do  begin    read(x,y);     ans:=1;    while y>0 do     begin        if y mod 2=1 then ans:=ans*x mod 99991;      y:=y div 2;      x:=(x*x) mod 99991; //设要mod的数为99991.     end;     writeln(ans);  end; end. 

一般的程序就是这样。

但为什么要设为99991呢?

变量要定义而pascal中的longint小于99990*99990所以一些特殊数据会报错,所以在编程时也要注意中间结果不能超过所定义变量的范围。

另:pascal中 a mod 2=a and 1;

                          a div 2=a shr 1;