HDU-#1061 Rightmost Digit(规律、分治、快速幂取模)

        题目大意:求N^N和10取余的结果。

       解题思路:该题有很多种做法,可以直接暴力(但会TLE)、找规律、分治、快速幂取模都可以求解。后三种求法都很快,其中找规律可以直接打表,速度很快,但规律一般不好找;分治类似于二分查找每次规模近似减少一半,时间复杂度为O(logn),快速幂取模的原理类似。详见code。

       题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=1061

       找规律 code:

#include <iostream>
#include <cstdio>
using namespace std;

int t,m,n;
const int ans[20] = { 0, 1, 4, 7, 6, 5, 6, 3, 6, 9, 0, 1, 6, 3, 6, 5, 6, 7, 4, 9 };

int main(){
    scanf("%d",&t);
    while (t--){
        scanf("%d",&n);
        printf("%d\n",ans[n%20]);
    }
    return 0;
}

       分治 code:

#include <iostream>
#include <cstdio>
using namespace std;

int t,m,n;
//直接暴力会TLE
//int main(){
//    scanf("%d",&t);
//    while(t--){
//        scanf("%d",&n);
//        ans=1;
//        for(int i=0;i<n;i++)
//            ans=(int)((long long)ans*n%10);
//        printf("%d\n",ans);
//    }
//    return 0;
//}

int pow_mod(int a,int n,int m){
    int x=1;
    if(n>0) x=pow_mod(a,n/2,m);
    long long ans = (long long)x*x%m;
    if(n%2==1) ans=ans*a%m;
    return (int)ans;
}

int main(){
    scanf("%d",&t);
    while(t--){
        scanf("%d",&n);
        int mod=pow_mod(n,n,10);
        printf("%d\n",mod);
    }
    return 0;
}

      快速幂取模 code(跟分治的原理一样):

#include <iostream>
#include <cstdio>
using namespace std;

int t,m,n;

int mod_exp(int a, int b, int m){
    int ans, tmp;
    ans=1%m;
    tmp=a%m;
    while (b){
        if (b&1) ans=ans*tmp%m;
        tmp=tmp*tmp%m;
        b >>= 1;
    }
    return ans;
}

int main(){
    scanf("%d",&t);
    while (t--){
        scanf("%d",&n);
        printf("%d\n",mod_exp(n, n, 10));
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值