gpt4 book ai didi

java - 求两个数的平方根数

转载 作者:行者123 更新时间:2023-11-30 06:10:03 25 4
gpt4 key购买 nike

我编写了这个函数来计算两个数字(包括)之间的平方根数。

static int FindRoot(int no1, int no2) {
int res = 0;
for (int x = no1; x <= no2; x++) {
for (int y = 1; y <= no2; y++) {
if (y * y == x)
res++;
}
}
return res;
}

这会很好用,但我在考虑它的性能。因为在这种情况下,内部 For 循环 将从起始位置 (1) 开始执行,所以如果有人将大范围的数字传递给该方法,将会花费一些时间。

所以,我的问题是:

Is there any other way i can find this with better performance?

P.S.- 我不能使用 Math.sqrt() 函数

最佳答案

static int FindRoot(int no1, int no2) {
int res = 0;
int x = 0;

// Ignore squares less than no1
while(x*x < no1) {
x++;
}

// Count squares up to and including no2
while(x*x <= no2) {
res++;
x++;
}

return res;
}

关于java - 求两个数的平方根数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36655126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com