728x90
반응형
아래 같은 방식으로 노가다로 풀 수도 있지만 수학으로 쉽게 풀 수 있는 문제다.
a, b = map(int, input().split())
a, b = min(a, b), max(a, b)
def f(n):
return (n*(n+1))//2
if a == b:
print(a)
elif a <= 0 and b >= 0:
print(f(b) - f(-a))
elif b <= 0:
print(-(f(-a) - f(-b-1)))
else:
print(f(b) - f(a-1))
수학이 참 좋은게 코드가 저렇게 짧아진다.
a, b = map(int, input().split())
a, b = min(a, b), max(a, b)
n = b - a
ans = ((n+1)*(n+2*a)) // 2
print(ans)
728x90
반응형
'Agorithm > 백준 알고리즘' 카테고리의 다른 글
백준 알고리즘 2438번 별 찍기(python) (0) | 2020.02.05 |
---|---|
백준 알고리즘 2407번 조합(python) (0) | 2020.02.05 |
백준 알고리즘 2292번 벌집(python) (0) | 2020.02.05 |
백준 알고리즘 2231번 분해합(python) (0) | 2020.02.05 |
백준 알고리즘 2217번 로프(python) (0) | 2020.02.05 |