Python 기초
파이썬, 0~100 짝수 합 구하는 다양한 방법
수알치
2019. 9. 27. 17:48
0~100 짝수 합 구하는 다양한 방법
글. 오상문 sualchi@daum.net
.
#방법1. 가장 느림 (for 반복문과 if 문장 이용)
total = 0
for i in range(1,101): # [1,2,3,4,...,100]
if i%2 == 0: # i가 짝수면
total += i # total = total + i
print(total)
#방법2. 보통 (for 반복문만 이용)
total = 0
for i in range(2, 101, 2): # [2,4,6,8,...,100]
total += i
print(total)
#방법3. 보통 (sum() 함수 이용)
print(sum(range(2,101,2)))
#방법4. 조금 빠름 (while 반복문 이용)
total = 0
n = 2
while n < 101: # while 반복문 이용
total += n
n += 2
print(total)
#방법5. 가장 빠름 (짝수 합 공식 이용)
n = 100//2 # n = 짝수 개수
print(n*(n+1)) # 짝수 합 공식
<이상>
반응형