次方求模

来源:互联网 发布:猎豹浏览器有mac版吗 编辑:程序博客网 时间:2024/05/29 11:44

1.例题


A^B Problem

时间限制:1000 ms  |  内存限制:65535 KB
难度:2
描述
Give you two numbers a and b,how to know the a^b's the last digit number.It looks so easy,but everybody is too lazy to slove this problem,so they remit to you who is wise.
输入
There are mutiple test cases. Each test cases consists of two numbers a and b(0<=a,b<2^30)
输出
For each test case, you should output the a^b's last digit number.
样例输入
7 668 800
样例输出
96
提示

There is no such case in which a = 0 && b = 0。

2.代码

#include <iostream>using namespace std;int f(int a, int b){    int r = 1;    while(b != 0)    {        if(b % 2 != 0)        {            r = r * a % 10;        }        a = a * a % 10;        b /= 2;    }    return r;}int main(){    int a,b;    while(cin>>a>>b)    {        cout<<f(a,b)<<endl;    }    return 0;}

3.例题

次方求模

时间限制:1000 ms  |  内存限制:65535 KB
难度:3
描述

求a的b次方对c取余的值

 

输入
第一行输入一个整数n表示测试数据的组数(n<100)
每组测试只有一行,其中有三个正整数a,b,c(1=<a,b,c<=1000000000)
输出
输出a的b次方对c取余之后的结果
样例输入
32 3 53 100 1011 12345 12345
样例输出
3110481

4.代码

 #include <iostream>#include <cstring>#include <cstdio>#include <cmath>#include <stack>#include <queue>using namespace std;long long int f(long long int a,long long int b,long long int c){    long long int r = 1;    while(b > 0)    {        if(b % 2 == 1)        {            r *= a;            r %= c;        }        b /= 2;        a *= a;        a %= c;    }    return r;}int main(){    long long int n,a,b,c;    cin>>n;    while(n--)    {        cin>>a>>b>>c;        cout<<f(a,b,c)<<endl;    }    return 0;}        


0 0
原创粉丝点击