天天看点

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