1.原题
Description
Current work in cryptography involves (among other things) large prime numbers and computing powers of numbers among these primes. Work in this area has resulted in the practical use of results from number theory and other branches of mathematics once considered to be only of theoretical interest. This problem involves the efficient computation of integer roots of numbers. Given an integer n>=1 and an integer p>= 1 you have to write a program that determines the n th positive root of p. In this problem, given such integers n and p, p will always be of the form k to the nth. power, for an integer k (this integer is what your program must find).
Input
The input consists of a sequence of integer pairs n and p with each integer on a line by itself. For all such pairs 1<=n<= 200, 1<=p<10101 and there exists an integer k, 1<=k<=109 such that kn = p.
Output
For each integer pair n and p the value k should be printed, i.e., the number k such that k n =p.
Sample Input
2 16
3 27
7 4357186184021382204544
Sample Output
4
3
1234
2.题意
简单来说,题意就是说给你M和N,然后要你求出K,使得K的M次方等于N
3.思路
由于结果的范围已经限制,是在1-10的9次方之间,很明显应该是用二分法来解决了,然后剩下的工作就是大数据的运算了,代码的话,我是从网上找的,思路的话,和我的思路基本一致
4.代码
#include <iostream>
#include <string.h>
using namespace std;
void swap_str(char str[]) {
int len = strlen(str);
for (int i=0; i<len/2; i++) {
int tmp = str[i];
str[i] = str[len-i-1];
str[len-i-1] = tmp;
}
}
void my_mul(char str[], int x) {
int len = strlen(str);
int cp = 0, i, tmp;
swap_str(str);
for (i=0; i<len; i++) {
tmp = (str[i]-'0')*x + cp;
str[i] = (tmp%10) + '0';
cp = tmp / 10;
}
while (cp) {
str[i++] = (cp%10) + '0';
cp /= 10;
}
while ('0'==str[i-1] && i>1)
i--;
str[i] = '\0';
swap_str(str);
}
int my_numCmp(char str1[], char str2[]) {
int len1, len2;
len1 = strlen(str1);
len2 = strlen(str2);
if (len1 > len2)
return 1;
if (len1 < len2)
return -1;
return strcmp(str1, str2);
}
void my_pow(char str[], int k, int n) {
str[0] = '1', str[1] = '\0';
while (n--) {
my_mul(str, k);
}
}
int my_binary_search(int n, char str[]) {
int high = 1e9, low = 0;
int mid;
char tot[2005];
while (low < high) {
mid = low + (high-low)/2;
my_pow(tot, mid, n);
int tmp = my_numCmp(tot, str);
if (0 == tmp)
return mid;
if (tmp < 0)
low = mid + 1;
else
high = mid;
}
return mid;
}
int main() {
char str[105];
int n;
while (scanf("%d%s", &n, str) != EOF) {
printf("%d\n", my_binary_search(n, str));
}
return 0;
}