javascript 查找给定数的最近平方数

ia2d9nvy  于 2023-02-07  发布在  Java
关注(0)|答案(6)|浏览(149)

任务是找到一个正整数n的最近的平方数nearest_sq(n)(取自codewars)。我已经尝试了下面的方法,但只是得到一个无限循环。

while(Math.sqrt(n)%1!==0){
    n-- || n++
}
return n;

有人能指出我在这段代码的逻辑上哪里错了吗?

kknvjkwl

kknvjkwl1#

应该很接近了

const nearest_sq = n => Math.pow(Math.round(Math.sqrt(n)), 2);

console.log(nearest_sq(117)); // 121
console.log(nearest_sq(900)); // 900
console.log(nearest_sq(15)); // 16
wb1gzix0

wb1gzix02#

求给定数的最近平方数的Python程序

from math import sqrt
def nearest_square(num):
         num1 = round(sqrt(num))**2
         return sqrt(num1)
print(nearest_square(48))
ct2axkht

ct2axkht3#

也许这不是捷径,但至少我认为代码很容易理解

function nearst_sq(n) {
  var nearstLow = nearst_low(n);
  var nearstHigh = nearst_high(n);

  return n-nearstLow < nearstHigh-n ? nearstLow : nearstHigh;
}

function nearst_high(n) {
  if (Math.sqrt(n)%1 === 0) {
    return n;
  }

  return nearst_high(++n);
}

function nearst_low(n) {
  if (Math.sqrt(n)%1 === 0) {
    return n;
  }

  return nearst_low(--n);
}
oalqel3c

oalqel3c4#

function nearestSq(n){
    let i,j;
    for(i=j=n;Math.sqrt(i)%1!=0&&Math.sqrt(j)%1!=0;i++,j--);
      return Math.sqrt(i)%1==0?i:j
    }
    console.log(nearestSq(21));
gblwokeq

gblwokeq5#

一个简单的Python3实现

from math import sqrt
nearestSqr = lambda x: round(sqrt(x)) ** 2
print(nearestSqr(99))
ev7lccsx

ev7lccsx6#

function nearestSq(n){
    
  let sqrtOfN=Math.trunc( Math.sqrt(n));
  let result=Math.abs((sqrtOfN*sqrtOfN)-n)>Math.abs((sqrtOfN+1)*(sqrtOfN+1)-n)?(sqrtOfN+1):sqrtOfN;
  if(sqrtOfN*sqrtOfN===n){
    result=n;
  }
else{
result=result*result;
}  
  return result;
  
}

相关问题