Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Kiểm tra số chính phương không dùng thư viện Math - JavaScript


Viết hàm JavaScript nhận vào một số, trả về boolean cho biết số đó có phải là số chính phương hay không.

Các ví dụ số chính phương: 4, 16, 81, 441, 256, 729, 9801.

Ví dụ

Mã thực hiện:

const num = 81; 
const isPerfectSquare = num => { 
  let ind = 1; 
  while(ind * ind <= num){ 
    if(ind * ind !== num){ 
      ind++; 
      continue; 
    }; 
    return true; 
  }; 
  return false; 
}; 
console.log(isPerfectSquare(81)); 
console.log(isPerfectSquare(9801)); 
console.log(isPerfectSquare(99)); 
console.log(isPerfectSquare(441)); 
console.log(isPerfectSquare(7648));

Kết quả

Kết quả in ra console:

true true false true false