문제
임의의 양의 정수 n에 대해, n이 어떤 양의 정수 x의 제곱인지 아닌지 판단하려 합니다.
n이 양의 정수 x의 제곱이라면 x+1의 제곱을 리턴하고, n이 양의 정수 x의 제곱이 아니라면 -1을 리턴하는 함수를 완성하세요.
제한조건
- n은 1이상, 50000000000000 이하인 양의 정수입니다.
입출력 예
풀이
integerSquareRoot.js1 2 3 4 5 6 7 8 9 10 11 12 13
| function integerSquareRoot(n) { let answer = 0; if (Math.sqrt(n) % 1 === 0) { answer = Math.pow(Math.sqrt(n) + 1, 2); } else { answer = -1; } return answer; }
export { integerSquareRoot };
|
integerSquareRoot.test.js1 2 3 4 5 6 7 8 9 10 11
| import { integerSquareRoot } from "../src/integerSquareRoot";
describe("integerSquareRoot", () => { it("should return the integer square root of a number", () => { expect(integerSquareRoot(121)).toBe(144); });
it("should return -1 if the number is not an integer square root", () => { expect(integerSquareRoot(3)).toBe(-1); }); });
|
출처
다른 풀이
1 2 3 4 5 6 7 8
| function nextSqaure(n){ switch(n % Math.sqrt(n)){ case 0: return Math.pow(Math.sqrt(n) + 1, 2); default: return "-1"; } }
|