首页 > ACM题库 > HDU-杭电 > HDU 2740-HOJ-Root of the Problem-数学相关-[解题报告]C++
2014
02-14

HDU 2740-HOJ-Root of the Problem-数学相关-[解题报告]C++

Root of the Problem

问题描述 :

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.

输入:

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).

输出:

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).

样例输入:

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

超级传送门:

http://acm.hdu.edu.cn/showproblem.php?pid=2740

 

题目大意:

给出B,N,求A,使得A^N最接近B ,不论大于或者小于

 

题目分析:

题目很好做,就是求出B的N次方根,分别向上取整和向下取整,看看那个更适合。

 

但是怎么实现捏?

pow(a,b)//求a^b,floor(a)//求a向下取整,ceil(a)//求a向上取整, 这几个函数帮上大忙了。。

由pow(a,b)//求a^b,得pow(a,1.0/b)//就是求a的b次方根了。。

于是代码秒杀了:

#include<iostream>
#include<cmath>
using namespace std;

int main()
{
	int B,N;
	double temp;
	int a1,a2;
	while(scanf("%d %d",&B,&N) != EOF)
	{
		if(B==0 && N==0) break;
		temp = pow(B+0.0,1.0/N);
		a1 = floor(temp);
		a2 = ceil(temp);
		if((B-pow(a1,N)) > (pow(a2,N) - B))
		{
			printf("%d\n",a2);
		}
		else
		{
			printf("%d\n",a1);
		}
	}
	return 0;
}

 

解题参考:http://blog.csdn.net/nikekkaa/article/details/6647691


  1. 题本身没错,但是HDOJ放题目的时候,前面有个题目解释了什么是XXX定律。
    这里直接放了这个题目,肯定没几个人明白是干啥

  2. 算法是程序的灵魂,算法分简单和复杂,如果不搞大数据类,程序员了解一下简单点的算法也是可以的,但是会算法的一定要会编程才行,程序员不一定要会算法,利于自己项目需要的可以简单了解。