对应POJ题目:点击打开链接
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 11962 | Accepted: 6409 |
Description
Given positive integers B and N, find an integer A such that AN is as close as possible to B. (The result A is an approximation to the Nth root of B.) Note that AN may be less than, equal to, or greater than B.
Input
The input consists of one or more pairs of values for B and N. Each pair appears on a single line, delimited by a single space. A line specifying the value zero for both B and N marks the end of the input. The value of B will be in the range 1 to 1,000,000 (inclusive), and the value of N will be in the range 1 to 9 (inclusive).
Output
For each pair B and N in the input, output A as defined above on a line by itself.
Sample Input
4 3 5 3 27 3 750 5 1000 5 2000 5 3000 5 1000000 5 0 0
Sample Output
1 2 3 4 4 4 5 16
题意:
给出B, N (B在[1, 1000000]内, N在[1, 9]内);求一个整数A, 使A^N最接近B。
思路:
从小到大枚举A,或者对[1, 1000000]进行二分,数据比较小。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define Min 1
#define Max 1000000
int b, n;
double My_pow(int a, int n)
{
if(1 == n) return (double)a;
if(n & 1){
double ans;
ans = My_pow(a, (n - 1) / 2);
return ans * ans * a;
}
else{
double ans;
ans = My_pow(a, n / 2);
return ans * ans;
}
}
void Bsearch(int l, int r, int *x, int *y)
{
while(l <= r){
int mid = ((l + r) >> 1);
double s = My_pow(mid, n);
if(s == (double)b){
*x = *y = mid;
break;
}
else if(s > (double)b){
*y = mid;
r = mid - 1;
}
else{
*x = mid;
l = mid + 1;
}
}
}
int main()
{
#if 0
freopen("in.txt","r",stdin);
#endif
while(scanf("%d%d", &b, &n), b && n){
int x = 1, y = 1;
Bsearch(Min, Max, &x, &y);
if(abs(My_pow(x, n) - b) < abs(My_pow(y, n) - b))
printf("%d\n", x);
else
printf("%d\n", y);
}
return 0;
}