算法提高 快速幂

来源:互联网 发布:mac怎么通过路径找文件 编辑:程序博客网 时间:2024/04/26 06:31

快速幂讲解http://blog.csdn.net/xuruoxin/article/details/8578992

问题描述
  给定A, B, P,求(A^B) mod P。
输入格式
  输入共一行。
  第一行有三个数,N, M, P。
输出格式
  输出共一行,表示所求。
样例输入
2 5 3
样例输出
2
数据规模和约定
  共10组数据
  对100%的数据,A, B为long long范围内的非负整数,P为int内的非负整数。
代码:

#include<iostream>#include<algorithm>#include<cmath>using namespace std;long long ksm(long long a, long long b, long long c){int ans = 1;a = a % c;while(b>0){if(b % 2 == 1)ans = (ans * a) % c;b = b/2;a = (a * a) % c;}return ans;}int main(){long long a,b,p;cin>>a>>b>>p;cout<<ksm(a,b,p);return 0;}


0 0
原创粉丝点击