TJU Root of the Problem

来源:互联网 发布:93国际大专辩论赛网络 编辑:程序博客网 时间:2024/05/17 21:45
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.


Example Input:Example Output:4 3
5 3
27 3
750 5
1000 5
2000 5
3000 5
1000000 5
0 01
2
3
4
4
4
5
16



题目意思:给定B和N,找到一个A,使得A的N次方离B最近(可能小于,等于,大于)。


解题思路:其实本题大可不必一个一个去试,这样会浪费很多的时间,而且效果不一定很好。既然题目中已经给出了B和N,就可以求出B的N次方根,这样可以将范围缩小在两个数。例如,对B求N次方根后,将其付给一个整形变量X,这样只需要检验X和X+1,其中必然有一个是所要求的结果。


源代码:


#include<iostream>
#include<cmath>
#define esp 1e-6
using namespace std;
int main()
{
    int B,N;
    while(cin>>B>>N&&B&&N)
    {
         int j=int (pow(1.0*B,1.0/N)+esp);
         double d1= B-pow(1.0*j,1.0*N);
         double d2= pow(1.0*(j+1),1.0*N)-B;
         if(d1<=d2)cout<<j<<endl;
         else cout<<j+1<<endl;
    }
    return 0;

原创粉丝点击