Two integers, left and right, are given as parameters. Complete the solution function to return the sum of numbers from left to right, where the count of divisors is even, and subtract the sum of numbers where the count of divisors is odd.
When I first encountered this question, my initial approach was to first find the divisors, then distinguish between even and odd counts, and finally proceed with addition and subtraction
def get_divisors(num):
divisors = []
for i in range(1, num + 1):
if num % i == 0:
divisors.append(i)
return divisors
After getting the divisors, I wasn't sure how to add extra fomular to distinguish between even and odd counts, so I searched on Google for a solution.
Google surprised me with a solution I hadn't thought of. All I needed to do was create one more function and add it. While I initially considered adding more fomular to the existing function, creating a new function for the additional task proved to be more efficient.
While solving the problem, I encountered various errors, but the final result turned out like this
def count_divisors(num):
count = 0
for i in range(1, num + 1):
if num % i == 0:
count += 1
return count
def solution(left, right):
answer = 0
for num in range(left, right + 1):
divisors_count = count_divisors(num)
if divisors_count % 2 == 0:
answer += num
else:
answer -= num
return answer
'Issue Note' 카테고리의 다른 글
Join And function (0) | 2024.04.19 |
---|---|
1934. Confirmation Rate (0) | 2024.04.12 |
Difference between 'num for num in range' and 'for num in range' (Python) (0) | 2024.04.02 |
Difference between list and [] (Python) (0) | 2024.04.02 |
DATE - [SQL} (0) | 2024.04.01 |