天天看點

7kyu You're a square!

題目:

A square of squares

You like building blocks. You especially like building blocks that are squares. And what you even like more, is to arrange them into a square of square building blocks!

However, sometimes, you can't arrange them into a square. Instead, you end up with an ordinary rectangle! Those blasted things! If you just had a way to know, whether you're currently working in vain… Wait! That's it! You just have to check if your number of building blocks is a perfect square.

你喜歡積木。你特别喜歡那些方形的積木。而你更喜歡的是,把它們排列成正方形的方塊! 但是,有時候,你不能把它們排列成正方形。相反,你最終會得到一個普通的矩形!這些混賬東西!如果你隻是想知道,你是否正在徒勞地工作……等等!就是這樣!你隻需要檢查一下你的積木的數量是不是一個完美的正方形。

Task

Given an integral number, determine if it's a square number:

給定一個整數,确定它是一個平方數:

In mathematics, a square number or perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself.

在數學中,一個平方數或一個平方數是整數的平方;換句話說,它是某個整數本身的乘積。

The tests will always use some integral number, so don't worry about that in dynamic typed languages.

測試總是使用一些整數,是以不要在動态類型語言中擔心這個問題。

Examples

isSquare(-1) // => false
isSquare( 3) // => false
isSquare( 4) // => true
isSquare(25) // => true
isSquare(26) // => false      

Sample Tests:

Test.describe("isSquare", function(){
  Test.it("should work for some examples", function(){
    Test.expect(!isSquare(-1), "Negative numbers cannot be square numbers");
    Test.expect(!isSquare( 3));
    Test.expect( isSquare( 4));
    Test.expect( isSquare(25));
    Test.expect(!isSquare(26));
  });
  Test.it("should work for random square numbers", function(){
    var r, i;
    for(i = 0; i < 100; ++i){
      r = (Math.random() * 0xfff0) | 0;
      Test.expect(isSquare(r*r), (r * r) + " is a square number");
    }
  });
});      

 答案:

var isSquare = function(n){
  var a = Math.sqrt(n);
  return a * a == n;
}      

轉載于:https://www.cnblogs.com/tong24/p/7397344.html