Leading and Trailing (快速幂+公式变形)

题目传送: UVA – 11029

思路:后三位可以直接快速幂取模,,然后前三位可以有两种做法,一个是利用double,一个是利用公式法,具体看代码吧

注意,后三位不足三位要补0,即用%03d

AC代码①:

#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#include <cmath>#include <queue>#include <stack>#include <vector>#include <map>#include <set>#include <deque>#include <cctype>#define LL long long#define INF 1000000000using namespace std;#define MOD 1000int T; int n, k;int kmod(int x, int n) {//快速幂 int ret = 1;while(n) {if(n & 1) ret = (ret * x) % MOD;x = (x * x) % MOD;n >>= 1;}return ret;}double kkmod(double x, int n) {//利用double来求前三位 double ret = 1;while(n) {if(n & 1) ret = ret * x;while(ret >= INF) ret /= INF;x = x * x;while(x >= INF) x /= INF;n >>= 1;}return ret;}int main() {scanf("%d", &T);while(T –) {scanf("%d %d", &n, &k);int ttt = n % 1000;ttt = kmod(ttt, k);double lll = kkmod((double)n, k);lll *= 1000;//可能lll本来就小于1000,可能还不足三位 while(lll >= 1000) {lll /= 10;}/*char str[1234];sprintf(str, "%lf", 1000 * lll);str[3] = '\0';*/ //也可以这样输出前三位 //printf("%lf\n", lll);printf("%d…%03d\n", (int)lll, ttt);//记住后三位用%03d,要严格按照格式输出 }return 0;}

AC代码②:

#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#include <cmath>#include <queue>#include <stack>#include <vector>#include <map>#include <set>#include <deque>#include <cctype>#define LL long long#define INF 0x7fffffffusing namespace std;int T;int n, k; int kmod(int x, int n) {int ret = 1;while(n) {if(n & 1) ret = (ret * x) % 1000;x = x * x % 1000;n >>= 1;}return ret;}int main() {scanf("%d", &T);while(T –) {scanf("%d %d", &n, &k);int lll, ttt;lll = kmod(n % 1000, k);ttt = (int)pow(10, 2 + fmod(k * log10(n), 1));//利用公式变形来求前三位 printf("%d…%03d\n", ttt, lll);}return 0; }

近朱者赤,近墨者黑

Leading and Trailing (快速幂+公式变形)

相关文章:

你感兴趣的文章:

标签云: