소수구하기(python 1929)
첫 풀이는 시간초과 발생
역시 정답률이 낮아서 그럴거같았다
M, N = map(int, input().split())
result = []
for i in range(M, N + 1, 1):
result.append(i)
for i in range(M, N + 1, 1):
if i < 2:
if i in result:
result.remove(i)
for j in range(2, int(i ** 0.5) + 1):
if i % j == 0:
if i in result:
result.remove(i)
break
for i in result:
print(i)
해결은 for-else 구문으로 코드를 간결화하여 성공
import math
M, N = map(int, input().split())
for i in range(M, N + 1, 1):
if i < 2:
continue
for j in range(2, int(math.sqrt(i)) + 1):
if i % j == 0:
break
else:
print(i)
for - else 구문
for loop 뒤에 else를 붙여주는 방식(else와 for은 같은 위치 선상에)
작동방식은 for문을 다 돌고 난 뒤 else 구문 내의 코드를 실행한다
이 for - else 구문은 break가 활용될 때 유용함
numbers = [1, 3, 5]
for number in numbers:
if number == 3:
break
else:
print("반복문 끝")
이런 방식으로 3이라는 값이 없으면 else가 리스트를 돌아 실행되는것
'algorithm' 카테고리의 다른 글
알고리즘 기초 1/2 300-수학: 팩토리얼 (0) | 2025.06.24 |
---|---|
알고리즘 기초 1/2 300-수학: 골드바흐의 추측 (0) | 2025.06.23 |
알고리즘 기초 1/2 300-수학: 소수찾기 (0) | 2025.06.11 |
알고리즘 기초 1/2 300-수학: 최소공배수 (0) | 2025.06.10 |
알고리즘 기초 1/2 300-수학: 최대공약수와 최소공배수 (0) | 2025.06.06 |