UVA 11029 Leading and Trailing

Problem C

Leading and Trailing

Time limit: 2 seconds

 

Apart from the novice programmers, all others know that you can’t exactly represent numbers raised to some high power. For example, the C function pow(125456, 455) can be represented in double data type format, but you won’t get all the digits of the result. However we can get at least some satisfaction if we could know few of the leading and trailing digits. This is the requirement of this problem.

 

Input

 

The first line of input will be an integer T<1001, where T represents the number of test cases. Each of the next T lines contains two positive integers, n and kn will fit in 32 bit integer and k will be less than 10000001.

 

Output

 

For each line of input there will be one line of output. It will be of the format LLL…TTT, where LLL represents the first three digits of n^k and TTT represents the last three digits of n^k. You are assured that n^k will contain at least 6 digits.

 

 

Sample Input

Output for Sample Input

2

123456 1

123456 2

123...456

152...936

 

题意:给定n,k求出n^k的前三位和后三位。

思路:后三位直接进行快速幂取模就可以。前三位的话要推一下。10^(x + y) = 10^x * 10 ^ y = lg n ^ k = k * lg n;x为整数位,y为小数位。这样等于只要求出y。然后取10^y前三位即可。

代码:

#include <stdio.h>
#include <math.h>

int T, n, k;

int Pow(int num, int k) {
	num %= 1000;
	if (k == 0) return 1;
	if (k % 2)
		return Pow(num * num, k / 2) * num % 1000;
	else
		return Pow(num * num, k / 2);
}

int solve() {
	double num = k * log(n) / log(10);
	double numm = num - (int)num;
	return (int)((pow(10, numm) + 1e-9) * 100);
}

int main() {
	scanf("%d", &T);
	while (T --) {
		scanf("%d%d", &n, &k);
		printf("%d...%03d\n", solve(), Pow(n, k));
	}
	return 0;
}



你可能感兴趣的:(UVA 11029 Leading and Trailing)