題目:dom
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.ui
你喜歡積木。你特別喜歡那些方形的積木。而你更喜歡的是,把它們排列成正方形的方塊! 可是,有時候,你不能把它們排列成正方形。相反,你最終會獲得一個普通的矩形!這些混帳東西!若是你只是想知道,你是否正在徒勞地工做……等等!就是這樣!你只須要檢查一下你的積木的數量是否是一個完美的正方形。spa
Given an integral number, determine if it's a square number:code
給定一個整數,肯定它是一個平方數:blog
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.ci
在數學中,一個平方數或一個平方數是整數的平方;換句話說,它是某個整數自己的乘積。數學
The tests will always use some integral number, so don't worry about that in dynamic typed languages.it
測試老是使用一些整數,因此不要在動態類型語言中擔憂這個問題。io
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; }