CSU 1347 Last Digit

本文介绍了一种高效算法,用于计算特定形式的数学函数f(n,k) = 1^k + 2^k + ... + n^k的最后一个数字。通过预先计算并利用模幂运算,该算法能在大规模输入范围内快速得出结果。

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

    The function f(n, k) is defined by f(n, k) = 1k + 2k + 3k +...+ nk. If you know the value of n and k, could you tell us the last digit of f(n, k)?
    For example, if n is 3 and k is 2, f(n, k) = f(3, 2) = 12 + 22 + 32 = 14. So the last digit of f(n, k) is 4.

Input

    The first line has an integer T (1 <= T <= 100), means there are T test cases.
    For each test case, there is only one line with two integers n, k (1 <= n, k <= 109), which have the same meaning as above.

Output

    For each test case, print the last digit of f(n, k) in one line.

Sample Input
10
1 1
8 4
2 5
3 2
5 2
8 3
2 4
7 999999997
999999998 2
1000000000 1000000000
Sample Output
1
2
3
4
5
6
7
8
9
0

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
ll mod_pow(ll x,ll n,ll mod){
	ll res=1;
	while(n>0){
		if(n&1) res=res*x%mod;
		x=x*x%mod;
		n>>=1;
	}
	return res;
}
int main()
{
	int T;
	scanf("%d",&T);
	ll a[10];
	//printf("==%lld\n",mod_pow(0,5,10));
	while(T--){
		ll n,k;
		scanf("%lld%lld",&n,&k);
		//memset(a,0,sizeof(a));
		ll sum=0;
		for(int i=0;i<10;i++){
			a[i]=mod_pow(i,k,10);
			//printf("++%lld\n",a[i]);
			sum=(sum+a[i])%10;
		}
		//printf("---%lld\n",sum);
		ll res=0;
		res=n/10*sum%10;
		//printf("res=%lld\n",res);
		for(int i=0;i<=n%10;i++){
			res+=a[i];
		}
		printf("%lld\n",res%10);
	}
	
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值