zoj2818 Root of the Problem 简单数学 开方

来源:互联网 发布:淘宝被恶意差评怎么办 编辑:程序博客网 时间:2024/06/05 20:26
Root of the Problem

Time Limit: 2 Seconds      Memory Limit:65536 KB

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 0
1
2
3
4
4
4
5
16

Source: Mid-Central USA 2006



第一思路:二分找最小k,k^m<=n,然后和(k+1)^m比较。


第二思路:我们都知道n的m次方为pow(n,m)——精确值,则n开m次方为pow(n,1/m)——近似值(有时会把结果拿回去验证一遍)。当然这个函数适用于小数据,int范围就最好。

#include<cstdio>#include<cstdlib>#include<iostream>#include<math.h>#include<algorithm>using namespace std;int main(){int n,m,k;while(cin>>n>>m){if(!n&&!m) return 0;k=pow(n,(double)1/m);if(pow(k+1,m)-n<n-pow(k,m)) k++;//求靠近的一个cout<<k<<endl;}return 0;}

原创粉丝点击