BEAKJOON
백준(1978번 소수 찾기)풀이 C++
Shin_jisoo
2021. 1. 13. 11:45
728x90
1978번: 소수 찾기
첫 줄에 수의 개수 N이 주어진다. N은 100이하이다. 다음으로 N개의 수가 주어지는데 수는 1,000 이하의 자연수이다.
www.acmicpc.net
1) 주석 없는 VERSION
#include <stdio.h>
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main() {
int n;
cin >> n;
int array[100] = { 0, };
int cnt = n;
for (int i = 0;i < n;i++) {
cin >> array[i];
if (array[i] == 1) {
cnt--;
}
}
for (int i = 0;i < n;i++) {
for (int j = 2;j <= sqrt(array[i]);j++) {
if (array[i] % j == 0) {
cnt--;
break;
}
}
}
cout << cnt;
}
2) 주석 있는 VERSION
//에라토스테네스의 소수 필요 충분조건은 그 숫자가 2보다 크면서
//자기 자신의 제곱근까지의 수에 나눠지지 않는 수
#include <stdio.h>
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main() {
//에라토스테네스의 소수 필요 충분조건은 그 숫자가 2보다 크면서
//자기 자신의 제곱근까지의 수에 나눠지지 않는 수
int n;
cin >> n;
int array[100] = { 0, };
int cnt = n;
for (int i = 0;i < n;i++) {
cin >> array[i]; // array에 숫자들 입력해주기
if (array[i] == 1) { // 1은 소수가 아니므로 count 빼기
cnt--;
}
}
for (int i = 0;i < n;i++) {
//2보다 크면서 그 수의 제곱근보다 작을 때까지의 수에 나누어 지는 수 count 빼기
for (int j = 2;j <= sqrt(array[i]);j++) {
if (array[i] % j == 0) {
cnt--;
break;
}
}
}
cout << cnt;
}