본문 바로가기
알고리즘/[python] 백준 BOJ

[python] 백준 1456 거의 소수

by Alan_Kim 2023. 2. 23.
728x90
반응형

https://www.acmicpc.net/problem/1456

 

1456번: 거의 소수

어떤 수가 소수의 N제곱(N ≥ 2) 꼴일 때, 그 수를 거의 소수라고 한다. 두 정수 A와 B가 주어지면, A보다 크거나 같고, B보다 작거나 같은 거의 소수가 몇 개인지 출력한다.

www.acmicpc.net

 

문제 해결

  • 편하게 0부터 끝 수(b)까지 리스트 만들어 놓고 하면 메모리 초과가 걸린다.
  • 따라서 int(sqrt(b))+1 개의 리스트 공간을 만들어 놓고 소수인 인덱스를 제곱, 세제곱 하면서 a와 b 사이에 들어오는지를 확인해야 할 것이다.

CODE

import math
import sys
input = sys.stdin.readline
a, b = map(int, input().split())
A = [0]*(int(math.sqrt(b))+1)
A[2] = 2
for i in range(3,len(A),2):
    A[i] = i

for i in range(3, int(math.sqrt(b))+1,2):
    if A[i] ==0: continue
    for j in range(i+i, int(math.sqrt(b))+1,i):
        A[j] = 0
count = 0

for i in range(2,int(math.sqrt(b))+1):
    if A[i] !=0:
        temp = A[i]
        while A[i] <= b/temp :
            if A[i] >= a/temp:
                count += 1
            temp = temp*A[i]
print(count)

 

 

728x90
반응형

댓글