求个位上的数字
比较简单,就是单独拿个位的数字来快速幂取模
#include <bits/stdc++.h>
using namespace std;
int ksm(long long x,int y,int m)//快速幂取模
{
int t;
if(y==0)
t=1;
else
{
t=ksm(x*x%m,y/2,m)%m;
if(y&1)
t=t*x%m;
}
return t;
}
int main()
{
int t;
while(cin >> t)
{
int n;
while(t--)
{
cin >> n;
long long x=n%10;//传入快速幂的是longlong
int ans=ksm(x,n,10);
cout << ans << endl ;
}
}
return 0;
}
.
求n^n的最大位上的数字
求一个x位的数字n^n的最大位上的数字求法:
设最大位的数字位a,则有 a=n^n/pow(10,x-1) 的取整值
如3^3的最大位=27/10的取整=2
其中,我们可以将分母再用一个pow来表示出来。
假定y=log10(n^n)=n*log10(n) (y位一个double)
则n^n=pow(10,y)
所以我们所求的a就能表示为
a=pow(10,y)/pow(10,x-1)=(int)pow(10,y-(x-1))
再将x和y带入表达式即可
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
while(cin >> t)
{
double n;
while(t--)
{
cin >> n;
double x1=n*log10(n); // 10的x1幂就是n^n
long long qua=(long long)x1+1; //数据是1e9的话这里要用longlong +1可以优化不要
int ans;
ans=(int)pow(10,x1-(qua-1)); //这里如果用double装,也可以求前x位
cout << ans << endl ;
}
}
return 0;
}