次方求模

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 66
8 800
样例输出
9
6
提示

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取余之后的结果
样例输入
3
2 3 5
3 100 10
11 12345 12345
样例输出
3
1
10481

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;
}
        


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值