查找数字是否为理想平方的优化方法 [英] Optimized way to find if a number is a perfect square
本文介绍了查找数字是否为理想平方的优化方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在分配作业中遇到一个问题,以确定一个数字是否完美的正方形:
I had a question in my assignment to find whether a number was perfect square or not:
完美平方是代数结构的元素,等于 另一个元素的平方.
Perfect square is an element of algebraic structure which is equal to the square of another element.
例如:4、9、16等.
For example: 4, 9, 16 etc.
我的朋友做的是,如果n
是数字,他们循环n - 1
次计算n * n
:
What my friends did is, if n
is the number, they looped n - 1
times calculating 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";
}
我想出了一个解决方案,如下所示:
I came up with a solution as shown below:
if (ceil(sqrt(n)) == floor(sqrt(n)))
{
std::cout << "Yes , it is";
}
else
{
std::cout << "no , it is not";
}
它正常工作.
与其他解决方案相比,它可以称为 更优化的解决方案 吗?
Can it be called as more optimized solution than others?
推荐答案
久经考验的事实仍然存在:
The tried and true remains:
double sqrt(double x); // from lib
bool is_sqr(long n) {
long root = sqrt(n);
return root * root == n;
}
这篇关于查找数字是否为理想平方的优化方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文