Java 求两个数之间的平方根数
我编写了这个函数来查找两个数字(包括)之间的平方根数Java 求两个数之间的平方根数,java,performance,for-loop,Java,Performance,For Loop,我编写了这个函数来查找两个数字(包括)之间的平方根数 静态int-FindRoot(int-no1,int-no2){ int res=0; 对于(intx=no1;x您可以通过去掉外部循环而不使用单个for循环 static int findRoot(int lo, int hi) { int numRoots = 0; for (int x = 0, x2 = 0; x2 <= hi; x++, x2 = x * x) { if (x2 >= l
静态int-FindRoot(int-no1,int-no2){
int res=0;
对于(intx=no1;x您可以通过去掉外部循环而不使用单个for循环
static int findRoot(int lo, int hi) {
int numRoots = 0;
for (int x = 0, x2 = 0; x2 <= hi; x++, x2 = x * x) {
if (x2 >= lo) {
numRoots++;
}
}
return numRoots;
}
静态int-findRoot(int-lo,int-hi){
int numRoots=0;
对于(int x=0,x2=0;x2=lo){
numRoots++;
}
}
返回numRoots;
}
在这里,您只需执行一次内部循环,当x2
(x平方)介于lo
和hi
之间时,增加numRoots
,并在x2
大于hi
时终止循环(而不是当x
大于代码中的hi
时){
int res=0;
int x=0;
//忽略小于1的方块
而(x*x
static int FindRoot2(int no1, int no2) {
int res = 0;
int inner=1;
for (int x = no1; x <= no2; x++) {
for (int y = inner; y <= no2; y++) {
if (y * y == x)
{
inner=y;
res++;
}
}
}
return res;
}
静态int-FindRoot2(int-no1,int-no2){
int res=0;
int-inner=1;
对于(int x=no1;x,当前算法无效的原因有很多,但最大的原因是不需要内部for循环
你正在寻找的算法背后的想法是,从高于或等于no1的最低完美正方形开始,然后进入下一个完美正方形,下一个和下一个,跟踪你击中的次数,直到你所处的完美正方形高于no2
static int FindRoot(int no1, int no2) {
int res = 0;
int x = 1;
// This loop gets x to the first perfect square greater than
// or equal to no1
while( (x * x) < no1 ) {
x++;
}
// This loop adds 1 to res and increases x
// as long as x^2 is less than or equal to no2
for(; (x * x) <= no2; x++, res++) { }
return res;
}
静态int-FindRoot(int-no1,int-no2){
int res=0;
int x=1;
//这个循环使x到达第一个大于
//或等于1号
而((x*x) 对于(;(x*x)你的函数只适用于完美的平方根?你可以围绕规则工作并实现计算平方根…但这可能不是你想要的:希望如此,它适用于我测试的少数情况。有什么问题吗?那么请帮我找出答案。Samyoun你有一个好主意当条件<代码时,你也可以打破你的内部循环>y*y您没有将零计算为可能的平方根。从“x=0,x2=0”开始。这确实会进行一些优化,但除了清晰、直接的O(n)解之外,没有理由使用其他解。
static int FindRoot2(int no1, int no2) {
int res = 0;
int inner=1;
for (int x = no1; x <= no2; x++) {
for (int y = inner; y <= no2; y++) {
if (y * y == x)
{
inner=y;
res++;
}
}
}
return res;
}
static int FindRoot(int no1, int no2) {
int res = 0;
int x = 1;
// This loop gets x to the first perfect square greater than
// or equal to no1
while( (x * x) < no1 ) {
x++;
}
// This loop adds 1 to res and increases x
// as long as x^2 is less than or equal to no2
for(; (x * x) <= no2; x++, res++) { }
return res;
}