1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #include<cstdio> int main(void) { int n,m,cnt; scanf("%d %d", &n, &m); for(int j=n; j<=m; j++) { cnt=0; for (int i=2; i<j; i++) { if (j%i == 0) cnt++; } if(cnt==0) printf("%d\n", j); } return 0; } | cs |
이 방법으로 풀면 이중for문 때문에 시간이 오래 걸려서 시간초과가 발생한다.
에라토스테네스의 채를 이용해서 풀어야함.
bool은 전역으로 선언하면 0이기 때문에 false임.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #include<cstdio> bool arr[1000002]; int main(void) { int n,m; scanf("%d %d", &m, &n); arr[1]=true; for(int i=2; i<=n; i++) for(int j=2; i*j<=n; j++) arr[i*j]=true; for (int i=m; i<=n; i++) if(arr[i]==false) printf("%d\n", i); return 0; } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #include<cstdio> bool arr[1000002]; int main(void) { int n,m; scanf("%d %d", &m, &n); arr[1]=true; for (int i = 2; i*i <= 1000000; i++) //2부터 1,000,000까지 체 돌리기 if (arr[i] == false) for (int j = i * i; j <= 1000000; j += i) //배수 구하기 arr[j] = true; for (int i=m; i<=n; i++) if(arr[i]==false) printf("%d\n", i); return 0; } | cs |
위에껀 32ms, 아래껀 12ms 걸림
'백준 1 > 수학' 카테고리의 다른 글
| [백준 2750] 수 정렬하기 (0) | 2020.12.05 |
|---|---|
| [백준 4948] 베르트랑 공준 (0) | 2020.12.05 |
| [백준 10867] 중복 빼고 정렬하기 (0) | 2020.12.05 |
| [백준 11004] k번째 수 (0) | 2020.12.05 |
| [백준 1065] 한수 (0) | 2020.12.05 |