새로새록
[c++]소수 찾기 본문
#include <iostream>
int main() {
int max_value;
std::cout << "Display primes up to what value? ";
std::cin >> max_value;
for (int value = 2; value <= max_value; value++) {
//가장 작은 소수는 2
bool is_prime = true;
for (int trial_factor = 2;
is_prime && trial_factor < value;
trial_factor++)
is_prime = (value % trial_factor != 0);
if (is_prime)
std::cout << value << " ";
}
std::cout << '\n';
}
#include<iostream>
using namespace std;
int main() {
int max_value;
cout << "Display primes up to what value?";
cin >> max_value;
int value = 2; //가장 작은 소수가 2임
while (value <= max_value) {
bool is_prime = true;
int trial_factor = 2;
while (trial_factor < value) {
if (value % trial_factor == 0) {
is_prime = false;
break;
}
trial_factor++;
}
if (is_prime)
cout << value << " ";
value++;
}
cout << endl;
}
#include <iostream>
#include <cmath>
bool is_prime(int n) {
bool result = true; //소수가정
double r = n, root = sqrt(r);
for (int trial_factor = 2;
result && trial_factor <= root; trial_factor++)
result = (n % trial_factor != 0);
return result;
}
int main() {
int max_value;
std::cout << "Display primes up to what value? ";
std::cin >> max_value;
for (int value = 2; value <= max_value; value++)
if (is_prime(value))
std::cout << value << " ";
std::cout << '\n';
}
벡터로 접근해서, 범위의 최소까지 정해줄 수 있다.
#include<iostream>
#include<vector>
#include<cmath>
using namespace std;
void print(const vector<int>& v) {
for (int elem : v)
cout << elem << " ";
cout << endl;
}
bool is_prime(int n) {
if (n < 2)
return false;
else {
bool result = true;
double r = n, root = sqrt(r);
for (int trial = 2;result & trial <= root;trial++)
result = (n % trial != 0);
return result;
}
}
vector<int> primes(int begin, int end) {
vector<int> result;
for (int i = begin; i <= end; i++)
if (is_prime(i))
result.push_back(i);
return result;
}
int main() {
int low, high;
cout << "please enter lowest and highest values in the range:";
cin >> low >> high;
vector<int> prime_list = primes(low, high);
print(prime_list);
}
'소프트웨어융합 > 경희대 c++ 과제' 카테고리의 다른 글
[c++]4. 검색엔진 - 키워드 포함 단어 (0) | 2020.07.14 |
---|---|
[c++]입력된 숫자들 중 가장 큰 값 max (0) | 2020.07.13 |
[c++]산모양 별트리 만들기 (0) | 2020.07.10 |
[c++] while(1) while(0), 무한루프에서 탈출하깅 (0) | 2020.07.10 |
[c++]타입캐스트 (0) | 2020.07.09 |