二分法-Rightmost Digit

来源:互联网 发布:零售 数据 算法 编辑:程序博客网 时间:2024/05/15 18:10

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

234
 

Sample Output

76

Hint


解题报告:快速幂模板题


code:

#include<iostream>#include<algorithm>#include<cstdio>#include<queue>#include<stack>#include<math.h>#include<string>#include<cstring>using namespace std;typedef long long ll;ll qm(ll a,ll n){ //a的n次方    ll sum=1;    while(n){        if(n&1)            sum=sum*a%10;        a=a*a%10;        n>>=1;    }    return sum%10;}int main(){  //  freopen("input.txt","r",stdin);    int t;    ll n;    scanf("%d",&t);    while(t--){        scanf("%lld",&n);        ll a=n%10;        printf("%lld\n",qm(a,n));    }}



*当然也可以找规律:

 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.


code:

#include <iostream>#include<algorithm>#include<stdio.h>using namespace std;typedef long long ll;ll qp(ll n,ll k){    if(!k) return 1;    ll ans=qp(n,k/2);    if(k%2!=0)        return (ans*ans%10)*n%10;    return ans*ans%10;}int main(){  //freopen("input.txt","r",stdin);   int t;   ll n,m;   cin>>t;   while(t--){        cin>>n;        m=n;        while(n%10!=0 && n>=10){            n=n%10;        }        cout<<qp(n,m)<<endl;   }return 0;}



0 0
原创粉丝点击