-
약수의 개수와 덧셈코딩 테스트/Level 1 2021. 7. 19. 22:53반응형
https://programmers.co.kr/learn/courses/30/lessons/77884
def solution(left, right): answer = 0 for each in range(left, right + 1): if count_divisor(each): answer += each else: answer -= each return answer def count_divisor(number): count = 0 for each in range(1, number + 1): if number % each == 0: count += 1 return count % 2 == 0
약수의 개수가 홀수인 수는 제곱근이 정수인 수입니다.
2: 1, 2
4: 1, '2', 4
8: 1, 2, 4, 8
16: 1, 2, '4', 8, 16def solution(left, right): answer = 0 for each in range(left, right + 1): if (temp := each ** 0.5) - int(temp) > 0: answer += each else: answer -= each return answer
def solution(left, right): return sum(each if (temp := each ** 0.5) - int(temp) > 0 else - each for each in range(left, right + 1))
PEP위반
solution = lambda left, right: sum(each if (temp := each ** 0.5) - int(temp) > 0 else - each for each in range(left, right + 1))
golang
import "math" func solution(left int, right int) (sum int) { for i := left; i <= right; i++ { temp := math.Sqrt(float64(i)) if temp-math.Trunc(temp) > 0 { sum += i } else { sum -= i } } return }
Java
class Solution { public int solution(int left, int right) { int answer = 0; for (var i = left; i < right + 1; i++) { var count = 0; for (var j = 1; j < i + 1; j++) { if (i % j == 0) { count++; } } if (count % 2 == 0) { answer += i; } else { answer -= i; } } return answer; } }
class Solution { public int solution(int left, int right) { int answer = 0; for (var i = left; i < right + 1; i++) { var temp = Math.sqrt(i); answer += (temp - (int) temp != 0) ? i : -i; } return answer; } }
반응형