LightOJ - 1282 Leading and Trailing (數學、快速冪)

題意:求n^k的前三位和後三位數字。


思路:n=10^a,a爲浮點數,則n^k=10^(a*k)=10^(x+y),x爲整數,y爲小數,則n^k前三位數字則爲10^y*100的整數部分,a可取log得出,y可由fomd()函數得。n^k的後三位則可有快速冪算出,模數爲1000,注意補足前導0。


#include <iostream>
#include <iomanip>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
#include <string>
#include <cmath>
#include <vector>
#include <utility>
#include <set>
#include <climits>
//#pragma comment(linker, "/STACK:1024000000,1024000000")
#define INF 2147483647
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 t,i,j;

int main()
{
    scanf("%d",&t);
    for(i=1;i<=t;i++)
    {
        ll num;
        int k;
        scanf("%lld%d",&num,&k);
        int nn=pow(10.0,2.0+fmod(log10(num)*k,1.0));//n^k的前三位
        int nn2=mod_pow(num,k,1000);
        printf("Case %d: %d %03d\n",i,nn,nn2);
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章