您的位置:首页 > 大数据 > 人工智能

UVA 11029 - Leading and Trailing

2013-05-02 12:48 316 查看
题目链接

这题后面3位可以用刘汝佳白书里面提到的快速幂取模方式求得,很简单。

至于前面三位,我看了一下别人的题解,都说的是用什么fmod()的方法,不太理解。不过参考了一下该方法:把一个数如123456变成1.23456X10^5的形式,要求它的前3位,则

乘以100就行了。于是我想到,如果求一个大数的n次方的时候,每次乘的都是一个小于10的数,比如123456对应于1.23456,然后每次乘完之后再控制一下位数:如果大于10了,则再除以10,这样不管是开多少次方不都不会溢出了吗?不过如果直接用for循环循环n次则肯定会比较慢,于是又用分治的方法写一个求幂的方法,提交,AC,时间是0.012s,也不算太慢,而且这个方法也容易理解一些。

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <vector>
#include <math.h>
#include <stack>
#include <map>
#include <queue>
#include <set>
#include <algorithm>
#include <time.h>
#include <iomanip>
#include <sstream>
#define SZ(v) ((int)(v).size())
#define REP(i, n) for (int i = 0; i < (n); ++i)
#define REPF(i, a, b) for (int i = (a); i <= (b); ++i)
#define REPD(i, a, b) for (int i = (a); i >= (b); --i)
#define MAX    1000000
#define INF 20000000
#define eps 1e-7
typedef long long ll;
typedef unsigned long long unll;
using namespace std;
const int maxint = -1u>>1;
const double PI = acos(-1.0);
char num[35];
int pow_mod(int a, int n, int m)
{
if(n == 1) return a%m;
int x = pow_mod(a, n/2, m);
ll ans = (ll)x * x % m;
if(n % 2 == 1) ans = ans * a % m;
return ans;
}
long double pow3(long double a, int n)
{
if(n == 1){
if(a >= 10) a /= 10.0;
return a;
}
if(a >= 10) a /= 10.0;
long double x = pow3(a, n/2);
if(x >= 10) x /= 10.0;
long double ans = x*x;
if(ans >= 10) ans /= 10.0;
if(n % 2 == 1) ans = ans * a;
if(ans >= 10) ans /= 10.0;
return ans;

}
int main()
{
//freopen("test.in", "r", stdin);
int n;
scanf("%d", &n);
while(n--)
{
int a, k;
scanf("%s %d", &num, &k);
a = (int)atof(num);
int ans = pow_mod(a, k, 1000);
int len = strlen(num);
double l = pow(10, len-1);
long double tmp = a/(double)l;			// 把数变为x.xxx形式
long double result = pow3(tmp, k);
int res = result*100;
printf("%d...%03d\n", res, ans);

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: