快速幂

来源:互联网 发布:软件开发界面 编辑:程序博客网 时间:2024/06/11 19:36
通用模板
int PowerMod(int a, int b, int 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;}

#include<stdio.h>int main(){int m, n;long res = 1, tmp = 1;scanf("%d %d",&m, &n);tmp = m;while(n){if(n%2 == 1){res =res*tmp;}tmp = tmp*tmp;n/=2;}printf("%ld",res);}



当时无聊还写了一个以3位基数来计算的,类似地以任何数为基数来讨论都可以,以N为基数就要讨论N-1种情况

#include<stdio.h>int main(){int background, power;scanf("%d %d", &background, &power);int tmp = background, result = 1;while(power){if(power%3 == 1){result *= tmp;}if(power%3 == 2){result *= tmp*tmp;}tmp *= tmp*tmp;power /= 3;}printf("%d", result);return 0;}


原创粉丝点击