我在作业中遇到了一个问题,要确定一个数字是否为 perfect square与否:
Perfect square is an element of algebraic structure which is equal to the square of another element.
例如:4、9、16等
我的 friend 所做的是,如果 n
是数字,他们循环 n - 1
次计算 n * n
:
// just a general gist
int is_square = 0;
for (int i = 2; i < n; i++)
{
if ((i * i) == n)
{
std::cout << "Yes , it is";
is_square = 1;
break;
}
}
if (is_square == 0)
{
std::cout << "No, it is not";
}
我想出了如下所示的解决方案:
if (ceil(sqrt(n)) == floor(sqrt(n)))
{
std::cout << "Yes , it is";
}
else
{
std::cout << "no , it is not";
}
而且它工作正常。
它可以被称为比其他更优化的解决方案吗?
最佳答案
久经考验的遗迹:
double sqrt(double x); // from lib
bool is_sqr(long n) {
long root = sqrt(n);
return root * root == n;
}
关于algorithm - 查找数字是否为完美正方形的优化方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25532306/