快速幂或找规律求a的b次方的最后一位-HDU1097

本文介绍了一种通过快速幂算法求解大数幂运算末位数字的方法,并给出了两种实现思路,一种是直接计算,另一种是利用循环特性进行优化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://vj.xtuacm.cf/contest/view.action?cid=125#problem/E

A hard puzzle
Problem Description
lcy gives a hard puzzle to feng5166,lwg,JGShining and Ignatius: gave a and b,how to know the a^b.everybody objects to this BT problem,so lcy makes the problem easier than begin.
this puzzle describes that: gave a and b,how to know the a^b’s the last digit number.But everybody is too lazy to slove this problem,so they remit to you who is wise.

Input
There are mutiple test cases. Each test cases consists of two numbers a and b(0


#include<cstdio>  
int mod(int a,int b,int k){  
    int ans=1;  
    a=a%k;  
    while(b>0){  
        if(b%2==1) ans=(ans*a)%k;  
        b/=2;  
        a=(a*a)%k;  
    }  
    return ans;  
}  
int main(){  
    int a,b;  
    while(scanf("%d%d",&a,&b)==2)  
        printf("%d\n",mod(a,b,10));  
    return 0;  
}  

这是直接的求法。看别人的题解,竟然还有一个规律:

尾数为0,1,5,6的不管是多少次方尾数依然不变,而尾数为4和9的每2次循环,

2,3,7,8为每4次循环。循环结果如下:

0,1,5,6:位数永远是0,1,5,6

2:6,2,4,8循环

3:1,3,9,7循环

4:6,4循环

7:1,7,9,3循环

8:6,8,4,2循环

9:1,9循环

好的,可以水过了:

#include<cstdio>  
int div[10]={1,1,4,4,2,1,1,4,4,2};  
int f[10][4]={{0},{1},{6,2,4,8},{1,3,9,7},{6,4},{5},{6},{1,7,9,3},{6,8,4,2},{1,9}};  
int main(){  
    int a,b;  
    while(scanf("%d%d",&a,&b)==2)  
        printf("%d\n",f[a%10][b%div[a%10]]);  
    return 0;  
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值