HDU_1061:Rightmost Digit
2024-09-06 14:52:45
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).
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
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.
最先想到的是一个一个算,但是由于数据范围太大,O(n^2)的时间复杂度对于n = 10亿时,10亿^10亿次乘法运算实在是不能忍受的。因此下面的程序超时(Time Limit Exceeded)。
#include<stdio.h>
int main(void)
{
int cases, n, copy_n, result;
scanf("%d", &cases);
while(cases--)
{
scanf("%d", &n);
copy_n = n;
n = n%;
result = ;
while(copy_n--)
{
result = (result*n)%;
}
printf("%d\n", result);
} return ;
}
下面,快速幂一来就AC了:
#include<stdio.h>
int my_power(int m, int n); // 求m的n次方的尾数
int main(void)
{
int cases, n;
scanf("%d", &cases);
while(cases--)
{
scanf("%d", &n);
printf("%d\n", my_power(n, n));
} return ;
} int my_power(int m, int n)
{
m = m%;
if(n == )
return m;
if(n% == )
return ( my_power(m*m, n/) ) % ;
else
return ( my_power(m*m, n/)*m ) % ;
}
可以看到,快速幂的时间复杂度是O(logn),n = 10亿时,大约32次递归调用就能出结果,效率极大的提高了。
最新文章
- hdoj 5500 Reorder the Books
- bzoj2004
- 利用R进行多元线性回归分析
- JQuery 判断IPad、IPhone、Android是横屏还是竖屏(Window.Orientation实现)
- vim的基本使用方法
- vue数组语法兼容问题
- 关于STM32的延时问题
- WebService技术简介
- Azure DevOps
- SSM商城项目(十三)
- 微信小程序onLaunch异步,首页onLoad先执行?
- codeforces 242E - XOR on Segment (线段树 按位数建树)
- GitHub 设置首页显示 404 There isn&#39;t a GitHub Pages site here.
- Openstack中查看虚拟机console log的几种方法
- MultiImageSelector 仿微信选择多张图片回调
- Add to Array-Form of Integer LT989
- Docker端口映射(六)
- Linux端口命令
- Block(二)内存管理与其他特性-b
- AppBox下调用HighCharts画曲线
热门文章
- Effective Modern C++ 条款1:理解模板型别推导
- 专访阿里云资深技术专家黄省江:中国SaaS公司的成功之路
- 图像通道、Scalar、分离、合成通道
- 作业-[luogu4396][AHOI2013]-莫队
- Hibernate: insert into xxx (name) values (?)但是数据库中没有数据
- Redhat/Fedora 或类似系统, 配置网络的工具介绍
- 阿里云SaaS生态战略发布:成就亿级营收独角兽
- 【python之路16】lambda表达式
- arcgis访问百度地图
- C# 模拟POST上传图片