임의의 양의 정수 n에 대해, n이 어떤 양의 정수 x의 제곱인지 아닌지 판단하려 합니다.
n이 양의 정수 x의 제곱이라면 x+1의 제곱을 리턴하고, n이 양의 정수 x의 제곱이 아니라면 -1을 리턴하는 함수를 완성하세요.
문제링크
풀이
1. 제곱근 x를 먼저 구하고 (x = n ** 1/2)
2. x 제곱이 n과 같다면 x+1 제곱 리턴
아니라면 -1 리턴 -> if
def solution(n):
x = int(n ** 0.5)
if x ** 2 == n:
answer = (x + 1) ** 2
else :
answer = -1
return answer
이것도 줄여서 표현해봤다
def solution(n):
x = int(n ** 0.5)
return (x + 1) ** 2 if x ** 2 == n else -1
다른사람 풀이
import math
def solution(n):
x = math.sqrt(n) # n의 제곱근을 구함
if x == int(x): # x가 정수인지 확인
return int((x + 1) ** 2)
else:
return -1
math
라이브러리import math
print(math.sqrt(64)) # 8.0 (제곱근)
print(math.factorial(5)) # 120 (5!)
print(math.gcd(36, 48)) # 12 (최대공약수)
print(math.sin(math.pi/2))# 1.0 (사인 90도)
print(math.log(100, 10)) # 2.0 (로그)
print(math.ceil(4.2)) # 5 (올림)
print(math.floor(4.9)) # 4 (내림)
print(math.e) # 2.718... (자연로그 e)
import math # 라이브러리 가져오기
math.sqrt(x) # x의 제곱근 반환