HDU 1061.Rightmost Digit题解

本文介绍了解决N^N次方最右位数问题的两种方法:快速幂求模算法和通过打表找规律的解法。快速幂求模算法利用位运算优化计算过程,大幅减少计算次数;而打表法则通过观察1-9结尾数字的循环周期,只需计算最多四次即可找出规律。

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

题目

Rightmost Digit

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 55522 Accepted Submission(s): 20987

Problem Description

Given a positive integer N, you should output the most right digit of N^N.

Input

The input contains several test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow.
Each test case contains a single positive integer N(1<=N<=1,000,000,000).

Output

For each test case, you should output the rightmost digit of N^N.

Sample Input

2
3
4

Sample Output

7
6

Hint

In the first case, 3 * 3 * 3 = 27, so the rightmost digit is 7. In the second case, 4 * 4 * 4 * 4 = 256, so the rightmost digit is 6.

大意:

看懂题很简单,就是n^n次方mod10

简单思路:pow函数直接暴力写,交了一发超时了。后面想到用快速幂求模,用的不是很熟练,参考了网上的题解。课后问别人发现可以直接打表找规律

———————————————————————————————————————————————————————

快速幂解法:

#include <iostream>
using namespace std;
int rightD(int n){//快速幂求模
	int ans=1;
	int tmp=n%10;
	while (n!=0){
		
		if(n&1==1)//判断二进制最后一位是不是1,等同于n%2==1;
			ans=(ans*tmp)%10;//如果是奇数就先乘一次,因为位运算会取整 
			
		tmp = (tmp*tmp)%10;//如果n是偶数,直接乘两倍,例如4*4==2*2*2*2,计算次数大幅减少 
		n = n>>1;//位运算,等同于n/=2; 例如1,2,4,8是做4次计算,倒着来8,4,2,1也是四次计算 
	} 
	return ans;
}
//主函数 
int main(){
	int numcount=0;//数字的个数
	int n=0;
	cin>>numcount;
	while (numcount-- > 0){
		cin>>n;
		cout<<rightD(n)<<endl;
	}
	return 0;
}

快速幂模板

ll pow(ll a,ll b,ll mod){
    ll ans=1;
    while(b!=0){
    
        if(b%2==1)
			ans=ans*a%mod;
			
        a=a*a%mod;
        b=b/2;
    }
    return ans;
}

————————————————————————————————————————————————————————

打表找规律解法:

1-9结尾的数中n^n尾数的最大循环周期是4
可以用n%4来计算n mod 4 的余数,然后每个数最多算四次循环即可

#include"bits/stdc++.h"
using namespace std;
int main(){
	int T;
	cin>>T;
	while(T--){
		int n;
		scanf("%d",&n);
		printf("%d\n",(int)pow(n%10, !(n%4) ? 4:n%4 ) %10);//判断n能不能被4整除,如果可以要n^4
	}													   //如果不能整除就n^(n mod 4),记得%10取最后一位 
}													       //pow函数胡返回值是double,用scanf输出要注意强制类型转换 

打表解法2

#include<stdio.h>
typedef long long ll;
int main(){
    int a[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}};//存以1-9结尾数的幂次尾数
    ll m;
    int n,i,h;
    while(~scanf("%d",&n)){
        for(int i=0;i<n;i++){
            scanf("%lld",&m);
            h=m%10;
            if(h==0||h==1||h==5||h==6)
                printf("%d",h);
            else if(h==4||h==9)
               printf("%d",a[h][m%2]);
            else
                printf("%d",a[h][m%4]);
                printf("\n");
            }
    }
   return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值