1. 程式人生 > >1347 Last Digit (數學規律)

1347 Last Digit (數學規律)

   The function f(nk) is defined by f(nk) = 1k + 2k + 3k +...+ nk. If you know the value of n and k, could you tell us the last digit of f(nk)?
    For example, if n is 3 and k is 2, f(nk) = f(3, 2) = 12 + 22 + 32 = 14. So the last digit of f(nk) 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 nk (1 <= nk <= 109), which have the same meaning as above.

Output

    For each test case, print the last digit of f(nk) 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<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define LL long long

const LL MAX = 1e6+10;
const LL INF = 0x3fffffff;

LL a[11][5];
LL b[10]={0,1,4,4,4,1,1,4,4,2};

int main(){
	for(LL i=0;i<11;i++)
		for(LL j=0;j<5;j++)
			a[i][j]=1;
	for(LL i=1;i<=10;i++){
		for(LL j=1;j<=4;j++){
			a[i][j] = (a[i][j-1]*i)%10;
		}
	}
	a[1][0]=1;
	a[2][0]=6;
	a[3][4]=1;
	a[4][0]=6;
	a[5][0]=5;
	a[6][0]=6;
	a[7][0]=1;
	a[8][0]=6;
	a[9][0]=1;
	LL t;
	cin>>t;
	while(t--){
		LL n,k;
		scanf("%lld%lld",&n,&k);
		LL nl = n/10;
		LL nv = n%10;
		LL te = 0;
		LL sum = 0;
		for(LL i=1;i<=nv;i++){
			sum += a[i][k%(b[i])];
			sum%=10;
		}
		if(nl<1){
			printf("%lld\n",sum);
		}
		else{
			LL temp = 0;
			for(LL i=1;i<=9;i++){
				temp += a[i][k%(b[i])];
				temp%10;
			}
			temp *= nl;
			temp+=sum;
			temp%=10;
			printf("%lld\n",temp);
		}
	}
	return 0;
}