LoginSignup
1
2

More than 5 years have passed since last update.

js 完全平方であるか判定し、真ならば次の完全平方を返す

Last updated at Posted at 2016-12-31

お題

与えられた引数が完全平方であるか判定し、真ならば次の完全平方を返す。
偽ならば-1を返す。
与えられる値は正の数とする。

*完全平方
ある整数・整式が他の整数・整式の平方になっていること。
→ √をとると、整数になる数。1,4,9,16,25,36,49…

function findNextSquare(sq) {
//write your code.
  return ;
}

出力結果 例

findNextSquare(121) // 144
findNextSquare(625) // 676
findNextSquare(114) // -1 

使ったもの

Math.sqrt()
Math.pow()

考え方

Math.sqrtで求めた平方根を変数に入れる。
変数の値が1で割りきれるか判定する。
0ならばMath.powで次の平方を求める。
割り切れない場合は-1を返しておわり。

コード

function findNextSquare(sq) {
  var root = Math.sqrt(sq);
  return root % 1 === 0 ? Math.pow(root + 1, 2) : -1;
}

他にもコードが浮かんだ方、コメントお待ちしております。

1
2
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2