728x90
반응형

문제 1. 팩토리얼

#include<iostream>

using namespace std;

int func_10872_factorial(int n) {
	if (n == 0) return 1;
	else return n * func_10872_factorial(n-1);
}

int main() {
	int a;
	cin >> a;

	cout << func_10872_factorial(a);
}

 

문제 2. 피보나치 수 5

#include<iostream>

using namespace std;

int func_10870_fibonacci(int n) {
	if (n == 0) return 0;
	if (n == 1) return 1;
	return func_10870_fibonacci(n - 1) + func_10870_fibonacci(n-2);
}


int main() {
	int a;
	cin >> a;

	cout << func_10870_fibonacci(a);
}

 

문제 3. 별 찍기 -10

 

 

문제 4. 하노이 탑 이동 순서

#include<iostream>

using namespace std;

void count_hanoi(int n){
	cout << (1 << n) -1 << "\n";
}

void hanoi(int n, int from, int to) {
	if (n == 1){
		cout << from << " " << to << "\n";
	}else{
		hanoi(n - 1, from, 6 - from - to);
		cout << from << " " << to << "\n";
		hanoi(n - 1, 6 - from - to, to);
	}
}

int main() {
	int n;
	cin >> n;

	count_hanoi(n);
	hanoi(n, 1, 3);
    
	return 0;
}

 

결과

728x90
반응형
728x90
반응형

문제 1. 소수찾기

#include<iostream>

typedef unsigned long long ll;

using namespace std;

int is_prime_number_custom(ll input)
{
    if (input < 2) {
        return 0;
    }

    for (ll j = 2; j <= (ll)(input / j); j++)
    {
        if (input % j == 0)
        {
            return 0;
        }
    }

    return 1;
}

int main() {
    int a, cnt=0;
    cin >> a;
    
    int* arr = new int[a];

    for (int i = 0; i < a; i++) {
        cin >> arr[i];
        if (is_prime_number_custom(arr[i])) {
            cnt++;
        }
    }

    cout << cnt;
    return 0;
}

 

문제 2. 소수

#include<iostream>

typedef unsigned long long ll;

using namespace std;

int is_prime_number_custom(ll input)
{
    if (input < 2) {
        return 0;
    }

    for (ll j = 2; j <= (ll)(input / j); j++)
    {
        if (input % j == 0)
        {
            return 0;
        }
    }

    return 1;
}
int main() {
    int a, b, min, sum = 0;
    cin >> a >> b;

    for (int i = a; i <= b; i++) {
        if (is_prime_number_custom(i)) {
            if (sum == 0) min = i;
            sum+=i;
        }
    }

    if (sum == 0) cout << -1 << endl;
    else {
        cout << sum << endl;
        cout << min;
    }
    return 0;
}

 

문제 3. 소인수분해

#include<iostream>

using namespace std;

void func_11653_Factorization(int a) {
    bool is_flag = true;

    for (int i = 2; i < a; i++) {
        if (a % i == 0) {
            is_flag = false;
            cout << i << endl;
            func_11653_Factorization(a / i);
            break;
        }
    }

    if(is_flag) cout << a << endl;
}

int main() {
    int a;
    cin >> a;

    if (a != 1) {
        func_11653_Factorization(a);
    }
    
    return 0;
}

 

문제 4. 소수 구하기

#include<stdio.h>
#include<math.h>

typedef unsigned long long ll;

int is_prime_number_custom(ll input)
{
    if (input < 2) {
        return 0;
    }

    for (ll j = 2; j <= (ll)(input / j); j++)
    {
        if (input % j == 0)
        {
            return 0;
        }
    }

    return 1;
}

int main() {
    int int_M, int_N;
    scanf("%d %d", &int_M, &int_N);
    
    for(int i = int_M; i <= int_N; i++)
    {
        if(is_prime_number_custom(i)){
            printf("%d\n", i);
        }
    }
    
    return 0;
}

 

문제 5. 베르트랑 공준

#include<iostream>
#include <cstring> 

using namespace std;

bool *Sieve_of_Eratosthenes(int m) {
    bool* arr = new bool[m + 1];

	memset(arr, 1, sizeof(bool) * (m+1));
	arr[0] = false;
	arr[0] = false;

    for (int i = 2; i < m + 1; i++) {
        if (arr[i] == true) {
            for (int j = i * 2; j < m + 1; j += i) {
                arr[j] = false;
            }
        }
    }

    return arr;
}

int main() {
    int int_N, cnt;
    bool* arr = Sieve_of_Eratosthenes(123456 * 2);

    do {
        cin >> int_N;
        cnt = 0;
        
        for (int i = int_N + 1; i <= int_N*2; i++)
        {
            if (arr[i]) {
                cnt++;
            }
        }

        if(int_N != 0) cout << cnt << endl;
    } while (int_N != 0);

    return 0;
}

 

문제 6. 골드바흐의 추측

#include<iostream>
#include<cstring>
#include<vector>

using namespace std;

bool *Sieve_of_Eratosthenes(int m) {
    bool* arr = new bool[m + 1];

    memset(arr, 1, sizeof(bool) * (m+1));
    arr[0] = false;
    arr[0] = false;

    for (int i = 2; i < m + 1; i++) {
        if (arr[i] == true) {
            for (int j = i * 2; j < m + 1; j += i) {
                arr[j] = false;
            }
        }
    }

    return arr;
}

int main() {
    int int_a, int_N, int_sum;
    bool* arr = Sieve_of_Eratosthenes(20000);
    int tmp_a, tmp_b, tmp_min;
    vector<int> v;

    cin >> int_a;
    for (int i = 0; i < int_a; i++) {
        cin >> int_N;

        int_sum = 0;
        v.clear();

        for (int j = 2; j < int_N; j++) {
            if (arr[j]) {
                v.push_back(j);
            }
        }

        tmp_a = 0;
        tmp_b = 0;
        tmp_min = int_N;

        for (int j = 0; j < v.size(); j++) {
            for (int k = 0; k < v.size(); k++) {
                if (int_N == v.at(j) + v.at(k) && tmp_min > abs(v.at(j) - v.at(k))) {
                    tmp_a = v.at(j);
                    tmp_b = v.at(k);
                    tmp_min = abs(v.at(j) - v.at(k));
                }
            }
        }

        if (tmp_a + tmp_b != 0) cout << tmp_a << " " << tmp_b << endl;
    }
    
    return 0;
}

 

문제 7. 직사각형에서 탈출

#include<iostream>

using namespace std;

int main() {
    int x, y, w, h, min;

    cin >> x;
    min = x;

    cin >> y;
    if (min > y) min = y;

    cin >> w;
    if (min > w-x) min = w-x;

    cin >> h;
    if (min > h - y) min = h - y;

    cout << min;
    return 0;
}

 

문제 8. 네 번째 점

#include<iostream>
#include<map>

using namespace std;

int main() {
    int a, b;
    map<int, int> x, y;
    map<int, int>::iterator iter;

    for (int i = 0; i < 3; i++) {
        cin >> a >> b;

        if (x.count(a)) x[a]++;
        else x[a] = 1;

        if (y.count(b)) y[b]++;
        else y[b]=1;
    }

    for (iter = x.begin(); iter != x.end(); iter++) {
        if (iter->second == 1) {
            cout << iter->first << " ";
        }
    }

    for (iter = y.begin(); iter != y.end(); iter++) {
        if (iter->second == 1) {
            cout << iter->first;
        }
    }
    
    return 0;
}

 

문제 9. 직각삼각형

#include<iostream>
#include<cmath>

using namespace std;

int main() {
    int a, b, c;
    int pow_a, pow_b, pow_c, pow_sum;

    while (1) {
        cin >> a >> b >> c;

        pow_a = pow(a, 2);
        pow_b = pow(b, 2);
        pow_c = pow(c, 2);
        pow_sum = pow_a + pow_b + pow_c;

        if (pow_sum == 0)
            break;

        if (pow_a == pow_sum - pow_a || pow_b == pow_sum - pow_b || pow_c == pow_sum - pow_c) {
            cout << "right" << endl;
        }
        else {
            cout << "wrong" << endl;
        }
    }
    
    return 0;
}

 

문제 10. 택시 기하학

#include<iostream>
#include<cmath>

using namespace std;

double const_pi() {
    return atan(1) * 4; 
}

int main() {
    int r;
    cin >> r;

    // 유클리드 기하학에서의 원의 넓이
    printf("%.6f\n", const_pi() * pow(r, 2));

    // 택시 기하학 에서의 넓이 : 대각선 길이가 2*r인 마름모의 넓이
    printf("%.6f\n", pow(2 * r, 2) / 2);
    
    return 0;   
}

 

문제 11. 터렛

#include<iostream>
#include<cmath>

using namespace std;

int main() {
    int a;
    cin >> a;

    int x1, y1, r1, x2, y2, r2;
    double len;

    for (int i = 0; i < a; i++) {
        cin >> x1 >> y1 >> r1 >> x2 >> y2 >> r2;

        // 두 점 사이의 거리
        len = sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2));

        // 반경이 완벽하게 겹치면 무한대의 경우
        if (len == 0 && r1 - r2 == 0) {
            cout << -1 << endl;
            continue;
        }

        // 시작점은 같은데 반경이 달라 만날 수 없음
        if (len == 0 && r1 - r2 != 0) {
            cout << 0 << endl;
            continue;
        }

        // 삼각형이 성립되면 2개, 일치하면 1개, 안되면 0개
        if (len < r1 + r2 && r1 < r2 + len && r2 < len + r1) {
            cout << 2 << endl;
        }
        else if (len == r1 + r2 || r1 == len + r2 || r2 == len + r1) {
            cout << 1 << endl;
        }
        else {
            cout << 0 << endl;
        }
    }
    return 0;
}

 

결과

 

 

728x90
반응형
728x90
반응형

문제 1. 손익분기점

#include <iostream>

using namespace std;

int main() {
	int a, b, c;
	cin >> a >> b >> c;
	int unit_profit = c - b;

	if (unit_profit <= 0) {
		cout << -1;
	}
	else {
		cout << a / unit_profit +1 << endl;
	}
    
	return 0;
}


/*
* 반복으로 문제를 풀 경우 시간 초과 발생
*/

 

문제 2. 벌집

#include <iostream>

using namespace std;

int main() {
	int a;
	cin >> a;
	
	for (int i = 1; true; i++) {
		if (a == 1) {
			cout << i;
			break;
		}

		a -= (6 * i);
		
		if (a <= 0) {
			cout << i+1;
			break;
		}
	}

	return 0;
}

/*
* 각 껍질당 1 -> 6 -> 12 -> 18 ... 로 6 * i 형태로 올라감
* 입력 받은 수에서 6 * i 씩 감소시켜 몇 칸을 지나는지 알수있음
* , 1일 경우 출력 후 바로 종료
*/

 

문제 3. 분수찾기

#include <iostream>

using namespace std;

unsigned long long func_1193_sum_of_arithmetic_sequences(int n) {
	return ( n * (n+1) ) / 2;
}

string func_1193_create(int n) {
	// 입력받은 인덱스를 규칙을 기반으로 생성 (입력시마다 생성, 모든 수가 비슷한 시간)
	// 규칙. 칸 수가 내려갈수록 1개씩 증가 1-> 2 -> 3 -> 4 ... 그리고 a/b 가 a는 증가, b는 감소
	int lv, pos;
	int a, b;

	// 계층 구하기
	for (int i = 0; i < 10000; i++) {
		if (n <= func_1193_sum_of_arithmetic_sequences(i)) {
			lv = i;
			break;
		}
	}

	// 계층과 차이나는 위치값 구하기
	pos = n - func_1193_sum_of_arithmetic_sequences(lv);

	// 시작지점의 값 설정
	if (lv % 2 == 0) {
		a = 1;
		b = lv;
		pos *= -1;
	}
	else {
		a = lv;
		b = 1;
	}

	// 차이나는 값 만큼 보정
	a += pos;
	b -= pos;

	return to_string(b) + "/" + to_string(a);
}

int main() {
	int a;
	cin >> a;

	cout << func_1193_create(a) << endl;
	return 0;
}

 

문제 4. 달팽이는 올라가고 싶다

#include <iostream>

using namespace std;

int main() {
	long long a, b, v, day;
	cin >> a >> b >> v;

	if (v <= a) {
		day = 1;
	}
	else {
		day = (v - b) / (a - b);
		if ((v - b) % (a - b) > 0) {
			day++;
		}
	}

	cout << day << endl;
    
	return 0;
}

 

문제 5. ACM 호텔

#include <iostream>

using namespace std;

int main() {
	int a, h, w, n;
	int f, no;

	cin >> a;

	for (int i = 0; i < a; i++) {
		f = 1;
		no = 1;
		cin >> h >> w >> n;

		f += (n % h) -1;
		if (n % h == 0) {
			f = h;
			no = n / h;
		}
		else {
			no += (n / h);
		}

		printf("%d%02d\n", f , no);
	}
}

 

문제 6. 부녀회장이 될테야

#include <iostream>

using namespace std;

int func_2775_sum_people(int k, int n) {
	if (k == 0) return n;
	if (n == 1) return 1;
	return func_2775_sum_people(k, n - 1) + func_2775_sum_people(k-1, n);
}

int main() {
	int int_k, int_n, int_t;

	cin >> int_t;

	for (int i = 0; i < int_t; i++) {
		cin >> int_k;
		cin >> int_n;

		cout << func_2775_sum_people(int_k, int_n) << endl;
	}
    
    return 0;
}

 

문제 7. 설탕배달

#include <iostream>

using namespace std;

int main() {
	int a, b, n, min, tmp, res;
	bool is_flag;

	cin >> n;

	min = n;
	res = -1;
	is_flag = false;

	for (int a = 0; a < n; a++) {
		for (int b = 0; b < n; b++) {
			tmp = (3 * a) + (5 * b);

			if (tmp > n) break;
			if (tmp == n) {
				if (min >= a + b) {
					min = a + b;
					is_flag = true;
				}
			}
		}
	}

	if (is_flag) res = min;

	cout << res << endl;
}

 

문제 8. 큰수 A+B

#include <iostream>
#include <vector>

using namespace std;

vector<int> func_10757_reverseVector(string num) {
	vector<int> v;

	for (int i = num.length() - 1; i >= 0; i--) {
		v.push_back( (num[i] - '0'));
	}

	return v;
}

int main() {
	string str_a, str_b;
	cin >> str_a >> str_b;

	vector<int> a, b, c;
	int int_a, int_b, int_tmp = 0, int_len;

	a = func_10757_reverseVector(str_a);
	b = func_10757_reverseVector(str_b);

	if (a.size() >= b.size()) {
		int_len = a.size();
	}
	else {
		int_len = b.size();
	}


	for (int i = 0; i < int_len; i++) {
		try {
			int_a = a.at(i);
		}
		catch (exception e) {
			int_a = 0;
		}

		try {
			int_b = b.at(i);
		}
		catch (exception e) {
			int_b = 0;
		}

		c.push_back((int_a + int_b + int_tmp) % 10);

		if ((int_a + int_b + int_tmp) >= 10) {
			int_tmp = 1;
		}
		else {
			int_tmp = 0;
		}
	}

	if (int_tmp) {
		c.push_back(1);
	}

	for (int i = c.size() - 1; i >= 0; i--) {
		cout << c.at(i);
	}
    
    return 0;
}

 

문제 9. Fly me to the Alpha Centauri

#include <iostream>
#include <cmath>

using namespace std;

typedef unsigned long long ll;

int main() {
    int int_case;
	ll x, y;
	ll res;
	ll distance, level;
	cin >> int_case;

	for (int i = 0; i < int_case; i++) {
		cin >> x >> y;
		distance = y - x;

		if (distance > 0 && distance <= 3) {
			res = distance;
		}
		else {
			level = (int)sqrt(distance);

			if (((level + 1) * (level + 1)) - (level+1) < distance && distance < ((level + 1) * (level + 1))) {
				res = 2 * level+1;
			}
			else if (distance == level * level ) {
				res = 2 * level -1;
			}
			else {
				res = 2 * level;
			}
		}

		cout << res << "\n";
	}
    return 0;
}

 

결과

 

728x90
반응형
728x90
반응형

문제 1. 아스키 코드

#include <iostream>

using namespace std;

int main() {
    cin.tie(NULL);
    cin.sync_with_stdio(false);

    char a;
    cin >> a;
    cout << int(a) << endl;

    return 0;
}

 

문제 2. 숫자의 합

#include <iostream>
#include <string>

using namespace std;

int main() {
    cin.tie(NULL);
    cin.sync_with_stdio(false);

    int a, sum=0;
    string b;
    cin >> a >> b;

    for (int i = 0; i < a; i++) {
        sum += int(b[i]) - int('0');
    }

    cout << sum << endl;

    return 0;
}

 

문제 3. 알파벳 찾기

#include <iostream>
#include <string>

using namespace std;

int main() {
    string s;
    int alphabets[26], index;
    int arr_size = sizeof(alphabets) / sizeof(int);

    for (int i = 0; i < arr_size; i++) {
        alphabets[i] = -1;
    }

    cin >> s;
    for (int i=0; i < s.size(); i++) {
        index = int(s[i]) - int('a');
        if (alphabets[index] == -1) {
            alphabets[index] += (i + 1);
        }
    }

    for (int i = 0; i < arr_size; i++) {
        cout << alphabets[i];
        if (i != arr_size - 1) cout << " ";
    }

    return 0;
}

 

문제 4. 문자열 반복

#include <iostream>

using namespace std;

int main(){
    int a, b;
	string str;

	cin >> a;

	for (int i = 0; i < a; i++) {
		cin >> b >> str;
		for (int i = 0; i < str.length(); i++) {
			for (int j = 0; j < b; j++) {
				cout << str[i];
			}
		}
		cout << endl;
	}
    
    return 0;
}

 

문제 5. 단어 공부

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <map> 
#include <utility>

using namespace std;

int main() {
	string str;
	map<char, int> myMap;
	map<char, int>::iterator iter;

	int int_max = 0;

	char ch_result;
	int int_cnt = 0;

	for (char c = 'a'; c <= 'z'; c++) {
		myMap[c] == 0;
	}

	cin >> str;
	for (int i = 0; i < str.length(); i++) {
		str[i] = tolower(str[i]);
		myMap[str[i]]++;
	}

	for (iter = myMap.begin(); iter != myMap.end(); iter++) {
		if (iter->second > int_max) {
			int_max = iter->second;
		}
	}

	for (iter = myMap.begin(); iter != myMap.end(); iter++) {
		if (int_max == iter->second) {
			int_cnt++;
			ch_result = iter->first;
		}
	}

	if (int_cnt == 1) {
		printf("%c\n", toupper(ch_result));
	}
	else {
		cout << '?' << endl;
	}

	return 0;
}

 

문제 6. 단어의 개수

#include <iostream>
#include <vector>
#include <string>
#include <sstream> 

using namespace std;

vector<string> func_1152_split(string str, char ch) {
	stringstream ss(str);
	string tmp;
	vector<string> res;

	while (getline(ss, tmp, ch)) {
		res.push_back(tmp);
	}

	return res;
}

int main() {
	string str;
	vector<string> res;
	int cnt = 0;

	getline(cin, str, '\n');
	res = func_1152_split(str, ' ');

	for (int i = 0; i < res.size(); i++) {
		if (res[i].size() > 0) cnt++;
	}

	cout << cnt << endl;
    return 0;
}

 

문제 7. 상수

#include<iostream>
#include<string>

using namespace std;

int main(){
	string a, b;
	string a_r, b_r;
	int res;
	int cnt=0;

	cin >> a >> b;

	a_r = a;
	b_r = b;

	for (int i = 2; i >= 0; i--) {
		a_r[cnt] = a[i];
		b_r[cnt++] = b[i];
	}
	
	if (stoi(a_r) > stoi(b_r)) {
		res = stoi(a_r);
	}
	else {
		res = stoi(b_r);
	}

	cout << res ;
    
    return 0;
}

 

문제 8. 다이얼

#include <iostream>
#include <string>
#include <map>

using namespace std;

int main(){
    string str;
	cin >> str;
	map<char, int> m;
	int point, sum=0;

	for (int i = 0; i < 26; i++) {	
		if ('A' + i < 'Z') point = 10;
		if ('A' + i < 'W') point = 9;
		if ('A' + i < 'T') point = 8;
		if ('A' + i < 'P') point = 7;
		if ('A' + i < 'M') point = 6;
		if ('A' + i < 'J') point = 5;
		if ('A' + i < 'G') point = 4;
		if ('A' + i < 'D') point = 3;

		m['A' + i] = point;
	}

	for (int i = 0; i < str.length(); i++) {
		sum += m[str[i]];
	}

	cout << sum << endl;
    
    return 0;
}

 

문제 9. 크로아티아 알파벳

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main() {
 	vector<string> v_str = { "c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z=" };
	string str;

	cin >> str;
	for (int i = 0; i < v_str.size(); i++) {
		while (1) {
			if (str.find(v_str[i]) == string::npos) {
				break;
			}
			else {
				str.replace(str.find(v_str[i]), v_str[i].length(), "!");
			}
		}
	}

	cout << str.length() << endl;
    return 0;
}

 

문제 10. 그룹 단어 체커

#include <iostream>
#include <string>
#include <map> 

using namespace std;

int main() {
    	int a;
	cin >> a;

	string* arr_str = new string[a];
	map<char, int> m;
	int cnt = 0;

	for (int i = 0; i < a; i++) {
		cin >> arr_str[i];
	}

	char pre_ch;
	bool is_flag;

	for (int i = 0; i < a; i++) {
		pre_ch = '0';
		is_flag = true;
		for (char ch = 'a'; ch <= 'z'; ch++) {
			m[ch] = 0;
		}

		for (int j = 0; j < arr_str[i].length(); j++) {
			if (m[arr_str[i][j]] != 0) {
				if (pre_ch != arr_str[i][j]) {
					is_flag = false;
					break;
				}
			}

			m[arr_str[i][j]]++;
			pre_ch = arr_str[i][j];
		}

		if (is_flag) {
			cnt++;
		}
	}
	
	cout << cnt;
	return 0;
}

 

결과

728x90
반응형
728x90
반응형

문제 1. 정수 N개의 합

#include <vector>

using namespace std;

long long sum(vector<int>& a) {
	long long ans = 0;

	for (int i = 0; i < a.size(); i++) {
		ans += a.at(i);
	}

	return ans;
}

 

문제 2. 셀프 넘버 

#include <iostream>
#include <string>
#include <cmath>

using namespace std;

int selfnumber(int a) {
    int digit = to_string(a).size(), tmp = 0, a_copy = a, sum = a;
    int* arr = new int[digit];
    
    for (int i = 0; i < digit; i++) {
        tmp = pow(10, (digit - (i + 1)));
        arr[i] = a_copy / tmp;
        a_copy %= tmp;
    }
    
    for (int i = 0; i < digit; i++) {
        sum += arr[i];
    }

    return sum;
}

int main() {
    int a = 10000;

    cin.tie(NULL);
    cin.sync_with_stdio(false);

    int* arr = new int[a];
    for (int i = 0; i < a; i++) {
        arr[i] = 0;
    }

    for (int i = 0; i < a; i++) {
        arr[selfnumber(i)-1]++;
    }

    for (int i = 0; i < a; i++) {
        if (arr[i] == 0) {
            cout << i+1 << endl;
        }
    }
    return 0;
}

 

문제 3. 한수

#include <iostream>
#include <string>
#include <cmath>

using namespace std;

bool hansu(int a) {
    bool is_flag = false;
    int tmp, cnt = 0;
    int digit = to_string(a).size();

    if (digit > 2) {
        int* arr = new int[digit];

        for (int i = 0; i < digit; i++) {
            tmp = pow(10, (digit - (i + 1)));
            arr[i] = a / tmp;
            a %= tmp;
        }

        int now_dif = 0;
        int pre_dif = arr[0] - arr[1];

        for (int i = 0; i < digit - 1; i++) {
            now_dif = arr[i] - arr[i + 1];
            if (now_dif == pre_dif) cnt++;
            pre_dif = now_dif;
        }

        if (digit - 1 == cnt) {
            is_flag = true;
        }
    }
    else {
        is_flag = true;
    }
    return is_flag;
}

int main() {
    int a = 0, cnt = 0;

    cin.tie(NULL);
    cin.sync_with_stdio(false);

    cin >> a;

    for (int i = 1; i <= a; i++) {
        if (hansu(i)) cnt++;
    }
    
    cout << cnt << endl;
    
    return 0;
}

 

결과

728x90
반응형
728x90
반응형

문제 1. 최소, 최대

#include <iostream>
#include <vector>

using namespace std;

int min(vector<int>& arr) {
    int min = arr.front();

    for (int i = 0; i < arr.size(); i++) {
        if (arr.at(i) < min) {
            min = arr.at(i);
        }
    }

    return min;
}

int max(vector<int>& arr) {
    int max = arr.front();

    for (int i = 0; i < arr.size(); i++) {
        if (arr.at(i) > max) {
            max = arr.at(i);
        }
    }

    return max;
}

int main() {
    int a, tmp;
    vector<int> arr;

    cin >> a;

    for (int i = 0; i < a; i++){
        cin >> tmp;
        arr.push_back(tmp);
    }

    cout << min(arr) << " " << max(arr);

    return 0;
}

 

문제 2. 최댓값

#include <iostream>
#include <vector>

using namespace std;

int main() {
    int tmp, max;
    vector<int> arr;

    for (int i = 0; i < 9; i++){
        cin >> tmp;
        arr.push_back(tmp);
    }

    max = arr.front();

    for (int i = 0; i < arr.size(); i++) {
        if (arr.at(i) >= max) {
            max = arr.at(i);
            tmp = i+1;
        }
    }

    cout << max << endl;
    cout << tmp;

    return 0;
}

 

문제 3. 숫자의 개수

#include <iostream>
#include <string>

using namespace std;

int main() {
    int a, b, c;
    int arr[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; 
    string str_abc;

    cin >> a >> b >> c;
    str_abc = to_string(a * b * c);

    for (int i = 0; i < str_abc.length(); i++) {
        arr[int(char(str_abc[i])) - int('0')]++;
    }

    for (int i = 0; i < 10; i++) {
        cout << arr[i] << endl;
    }

    return 0;
}

 

문제 4. 나머지

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    vector<int> arr;
    int a;

    for (int i = 0; i < 10; i++) {
        cin >> a;
        arr.push_back(a % 42);
    }

    sort(arr.begin(), arr.end());
    arr.erase(unique(arr.begin(), arr.end()), arr.end());

    cout << arr.size() << endl;
    return 0;
}

 

문제 5. 평균

#include <iostream>

using namespace std;

int main() {
    int a, max;
    double aver=0;

    cin >> a;
    int* arr = new int[a];
    double* arr2 = new double[a];

    for (int i = 0; i < a; i++) {
        cin >> arr[i];

        if (i == 0) {
            max = arr[0];
        }

        if (arr[i] > max) {
            max = arr[i];
        }
    }

    for (int i = 0; i < a; i++) {
        arr2[i] = double(arr[i]) / max * 100;
    }

    for (int i = 0; i < a; i++) {
        aver += arr2[i];
    }

    cout.precision(6);
    cout << aver / a << endl;

    return 0;
}

 

문제 6. OX퀴즈

#include <iostream>

using namespace std;

int point(string str) {
    bool is_flag = false;
    int cnt = 1, sum = 0;

    for (int i = 0; i <= str.size(); i++) {
        if (str[i] == 'O') {
            if(is_flag) cnt++;
            is_flag = true;
            sum += cnt;
        }
        else {
            cnt = 1;
            is_flag = false;
        }
    }

    return sum;
}

int main() {
    int a;
    cin >> a;
    int* arr = new int[a];
    string* str_arr = new string[a];

    for (int i = 0; i < a; i++) {
        cin >> str_arr[i];
    }

    for (int i = 0; i < a; i++) {
        cout << point(str_arr[i]) << endl;
    }

    return 0;
}

 

문제 7. 평균은 넘겠지

#include <iostream>
#include <vector>
#include <stdio.h>

using namespace std;

int main() {
    int a, b, sum, cnt, all;
    double aver;
    cin >> a;
    vector<int *> vec;
    char str_tmp[100];
    
    for (int i = 0; i < a; i++) {
        cin >> b;
        int* arr = new int[b + 1];
        arr[0] = b;

        for (int j = 1; j <= b; j++) {
            cin >> arr[j];
        }

        vec.push_back(arr);
    }

    for (int i = 0; i < vec.size(); i++) {
        all = int(vec.at(i)[0]); 
        sum = 0;
        for (int j = 1; j <= all; j++) {
            sum += vec.at(i)[j];
        }
        aver = double(sum) / all;

        cnt = 0;
        for (int j = 1; j <= all; j++) {
            if (aver < vec.at(i)[j]) {
                cnt += 1;
            }
        }
        
        sprintf(str_tmp, "%.3f", double(cnt) / all * 100);
        cout << str_tmp << "%" << endl;
    }
    
    return 0;
}

 

결과

728x90
반응형
728x90
반응형

문제 1. A+B - 5

#include <iostream>

using namespace std;

int main() {
    int a, b;

    while (true) {
        cin >> a >> b;

        if (a + b == 0) {
            break;
        }

        cout << a + b << endl;
    }
    
    return 0;
}

 

문제 2. A+B - 4

#include <iostream>

using namespace std;

int main() {
    int a, b;

    while (cin >> a >> b) {
        cout << a + b << endl;
    }
    
    return 0;
}

 

문제 3. 더하기 사이클

#include <iostream>

using namespace std;

void func(int a, int *front, int *back) {
    if (a < 10) {
        if(front) *front = 0;
        if(back) *back = a;
    }
    else {
        if (front) *front = a / 10;
        if (back) *back = a % 10;
    }
}

int main() {
    int a, b, cycle = 0;
    int front_a, back_a, back_b;

    cin >> a;
    b = a;

    do {
        func(b, &front_a, &back_a);
        func(front_a + back_a, NULL, &back_b);
        
        b = back_a * 10 + back_b;
        
        cycle++;
    } while (a != b);

    cout << cycle;

    return 0;
}

 

결과

728x90
반응형
728x90
반응형

문제 1. 구구단

#include <iostream>

using namespace std;

int main() {
    int a;

    cin >> a;

    for (int i=1; i<10; i++) {
        cout << a << " * " << i << " = " << a * i << endl;
    }

    return 0;
}

 

문제 2. A+B - 3

#include <iostream>

using namespace std;

int main() {
    int cnt=0, a, b;

    cin >> cnt;
    int *arr = new int[cnt];

    for (int i = 0; i < cnt; i++) {
        cin >> a >> b;
        arr[i] = a + b;
    }

    for (int i = 0; i < cnt; i++) {
        cout << arr[i] << endl;
    }

    return 0;
}

 

문제 3. 합

#include <iostream>

using namespace std;

int main() {
    int a, sum=0;

    cin >> a;

    for (int i = 1; i <= a; i++) {
        sum += i;
    }

    cout << sum;

    return 0;
}

 

문제 4. 빠른 A+B

#include <iostream>

using namespace std;

int main() {
    int cnt = 0, a, b;

    cin.tie(NULL);
    cin.sync_with_stdio(false);

    cin >> cnt;
    int* arr = new int[cnt];

    for (int i = 0; i < cnt; i++) {
        cin >> a >> b;
        arr[i] = a + b;
    }

    for (int i = 0; i < cnt; i++) {
        cout << arr[i] << "\n";
    }

    return 0;
}

 

문제 5. N 찍기

#include <iostream>

using namespace std;

int main() {
    int cnt = 0;

    cin.tie(NULL);
    cin.sync_with_stdio(false);

    cin >> cnt;

    for (int i = 1; i <= cnt; i++) {
        cout << i << "\n";
    }

    return 0;
}

 

문제 6. 기찍 N

#include <iostream>

using namespace std;

int main() {
    int cnt = 0;

    cin.tie(NULL);
    cin.sync_with_stdio(false);

    cin >> cnt;

    for (int i = cnt; i > 0; i--) {
        cout << i << "\n";
    }

    return 0;
}

 

문제 7. A+B - 7

#include <iostream>

using namespace std;

int main() {
    int cnt = 0, a, b;

    cin >> cnt;
    int* arr = new int[cnt];

    for (int i = 0; i < cnt; i++) {
        cin >> a >> b;
        arr[i] = a + b;
    }

    for (int i = 0; i < cnt; i++) {
        cout << "Case #" << i+1 << ": "<< arr[i] << endl;
    }

    return 0;
}

 

문제 8. A+B - 8

#include <iostream>

using namespace std;

int main() {
    int cnt = 0;

    cin >> cnt;
    int* arr = new int[cnt];
    int* a = new int[cnt];
    int* b = new int[cnt];

    for (int i = 0; i < cnt; i++) {
        cin >> a[i] >> b[i];
        arr[i] = a[i] + b[i];
    }

    for (int i = 0; i < cnt; i++) {
        cout << "Case #" << i+1 << ": " << a[i] << " + " << b[i] << " = " << arr[i] << endl;
    }

    return 0;
}

 

문제 9. 별 찍기 - 1

#include <iostream>

using namespace std;

int main() {
    int cnt = 0;

    cin >> cnt;

    for (int i = 0; i < cnt; i++) {
        for (int j = 0; j <= i; j++) {
            cout << "*";
        }
        cout << "\n";
    }

    return 0;
}

 

문제 10. 별 찍기 - 2

#include <iostream>

using namespace std;

int main() {
    int cnt = 0;

    cin >> cnt;

    for (int i = 1; i <= cnt; i++) {
        for (int j = cnt; j >= 1; j--) {
            if (i < j) {
                cout << " ";
            }
            else {
                cout << "*";
            }
        }
        cout << "\n";
    }

    return 0;
}

 

문제 11. X보다 작은 수

#include <iostream>

using namespace std;

int main() {
    int n, x;
    cin >> n >> x;

    int* arr = new int[n];

    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }

    for (int i = 0; i < n; i++) {
        if (arr[i] < x) {
            cout << arr[i];
            if (i != n - 1) {
                cout << " ";
            }
        }
    }


    return 0;
}

 

결과

728x90
반응형
728x90
반응형

문제 1. 두 수 비교하기

#include <iostream>

using namespace std;

int main() {
    int a, b;

    cin >> a;
    cin >> b;

    if (a > b) {
        cout << ">";
    }
    else if (a < b) {
        cout << "<";
    }
    else {
        cout << "==";
    }

    return 0;
}

 

문제 2. 시험 성적

#include <iostream>

using namespace std;

int main() {
    int a;
    string b = "F";

    cin >> a;

    if (a >= 60) {
        b = "D";
    }
    if (a >= 70) {
        b = "C";
    }
    if (a >= 80) {
        b = "B";
    }
    if (a >= 90) {
        b = "A";
    }

    cout << b;

    return 0;
}

 

문제 3. 윤년

#include <iostream>

using namespace std;

int main() {
    int a, answer = 0;
    cin >> a;

    if(a % 4 == 0 && a % 100 != 0) {
        answer = 1;
    }
    if (a % 400 == 0) {
        answer = 1;
    }

    cout << answer;

    return 0;
}

 

문제 4. 사분면 고르기

#include <iostream>

using namespace std;

int main() {
    int x, y, answer = 0;
    cin >> x;
    cin >> y;

    if (x > 0 && y > 0) {
        answer = 1;
    }
    if (x < 0 && y > 0) {
        answer = 2;
    }
    if (x < 0 && y < 0) {
        answer = 3;
    }
    if (x > 0 && y < 0) {
        answer = 4;
    }

    cout << answer;

    return 0;
}

 

문제 5. 알람 시계

#include <iostream>
#include <stdio.h>

using namespace std;

int main() {
    int h, m;
    char answer[30] = "";

    cin >> h;
    cin >> m;

    m -= 45;

    if (m >= 60) {
        m -= 60;
        h += 1;
    }
    if (m < 0) {
        m = 60 + m;
        h -= 1;
    }

    if (h >= 24) {
        h -= 24;
    }
    if (h < 0) {
        h = 24 + h;
    }

    snprintf(answer, 30, "%d %d", h, m);
    cout << answer;

    return 0;
}

 

추가 문제 6. 오븐 시계 (브론즈 4, 2022-02-16 확인)

#include<iostream>

using namespace std;

int main() {
	int a, b, c;
	cin >> a >> b >> c;

	b = b + c;
	if (b < 0) {
		b = 0;
	}
	while (b >= 60) {
		b -= 60;
		a += 1;
	}

	if (a < 0) {
		a = 0;
	}
	while (a >= 24) {
		a -= 24;
	}

	cout << a << " " << b << "\n";
    
    return 0;
}

 

추가 문제 7. 주사위 세개(브론즈 4, 2022-02-16)

#include<iostream>
#include<map>

using namespace std;

int main() {
	map<int, int> m;
	int a, res=0, k_max = 0, v_max = 0;

	for (int i = 0; i < 3; i++) {
		cin >> a;
		m[a]++;
		if (k_max < a) k_max = a;
		if (v_max < m[a]) v_max = m[a];
	}

	for (auto v : m) {
		if (v_max != 1 && v_max == v.second) {
			k_max = v.first;
		}
	}

	if (v_max == 3) {
		res = 10000 + k_max * 1000;
	}
	if (v_max == 2) {
		res = 1000 + k_max * 100;
	}
	if (v_max == 1) {
		res = k_max * 100;
	}

	cout << res << "\n";
    
    return 0;
}

 

 

결과

728x90
반응형
728x90
반응형

문제 1. Hello World

#include <iostream>

int main(){
    std::cout << "Hello World!";
    
    return 0;
}

 

문제 2. We love krill

#include <iostream>

int main(){
    std::cout << "강한친구 대한육군";
    std::cout << "강한친구 대한육군";
    
    return 0;
}

 

문제 3. 고양이

#include <iostream>

using namespace std;

int main() {
    cout << "\\    /\\\n";
    cout << " )  ( ')\n";
    cout << "(  /  )\n";
    cout << " \\(__)|\n";
    
    return 0;
}

 

문제 4. 개

#include <iostream>
using namespace std;

int main(){
    cout << "|\\_/|\n";
    cout << "|q p|   /}\n";
    cout << "( 0 )\"\"\"\\\n";
    cout << "|\"^\"`    |\n";
    cout << "||_/=\\\\__|\n";
    
    return 0;
}

 

문제 5. A+B

int main(){
    int a, b;
    
    scanf("%d %d", &a, &b);
    printf("%d", a+b);
    
    return 0;
}

 

문제 6. A-B

int main(){
    int a, b;
    
    scanf("%d %d", &a, &b);
    printf("%d", a-b);
    
    return 0;
}

 

문제 7. A*B

#include <iostream>

int main(){
    int A, B;
    
    std::cin >> A >> B;
    std::cout << A * B;
    
    return 0;
}

 

문제 8. A/B

#include <iostream>

using namespace std;

int main() {
    double a, b;
    cin >> a >> b;
    
    printf("%.10f", a / b);

    return 0;
}

 

문제 9. 사칙연산

#include <iostream>

using namespace std;

int main() {
    int a, b;
    cin >> a >> b;
    
    cout << a + b << endl;
    cout << a - b << endl;
    cout << a * b << endl;
    cout << a / b << endl;
    cout << a % b << endl;

    return 0;
}

 

문제 10. 나머지

#include <iostream>

using namespace std;

int main() {
    int a, b, c;
    cin >> a >> b >> c;
    
    cout << (a + b) % c << endl;
    cout << ((a%c) + (b%c))%c << endl;
    cout << (a * b)%c << endl;
    cout << ((a % c) * (b % c)) % c << endl;

    return 0;
}

 

문제 11. 곱셈

#include <iostream>

using namespace std;

int main() {
    int a, b, c;
    int b1, b2, b3;

    cin >> a;
    cin >> b;

    c = a * b;
    b3 = a * (b / 100);
    b %= 100;
    b2 = a * (b / 10);
    b %= 10;
    b1 = a * b; 

    cout << b1 << endl;
    cout << b2 << endl;
    cout << b3 << endl;
    cout << c << endl;

    return 0;
}

 

결과

728x90
반응형
728x90
반응형

1. lambda 표현식 요약

- 함수를 하나의 식으로 표현한 것으로 다른 함수의 매개변수로 전달이 가능함

- 함수의 이름이 없기 때문에 익명 함수라고도 불림

- 함수 표현식 사용할 경우 속도가 저하된다고 함 (정확하지 않음, 재확인 필요)

 

2. 사용법 

# Case 1. lambda 함수 정의 후 매개변수 전달
function_lambda = lambda x : x + 1
print("result : ", function_lambda(1))
# result : 2

# Case 2. 한번에 매개변수 전달
print("result : ", (lambda x : x + 1)(1))
# result : 2

# Case 3. 외부 변수 활용
y = 1
print("result : ", (lambda x : x + y)(1))
# result : 2

# Case 4. 여러개의 매개변수 전달
print("result : ", (lambda x, y : x + y)(1, 1))
# result : 2

# Case 5. max 함수의 매개 변수로 사용
print(max((lambda x : [i for i in range(1, x+1)])(10)))
# 10

 

728x90
반응형

'프로그래밍 > Python' 카테고리의 다른 글

[Python] Paramiko 모듈  (0) 2022.07.07
[Python] 데코레이터 (@, Decorator)  (0) 2022.03.21
[Python] min, max 함수  (0) 2022.03.10
[python] 실행 시 필요한 패키지 자동 설치  (0) 2022.01.01
[Python] FinanceDataReader 모듈  (0) 2021.07.31
[Python] pykrx 모듈  (0) 2021.05.27
728x90
반응형

https://en.wikipedia.org/wiki/WireGuard

 

WireGuard - Wikipedia

From Wikipedia, the free encyclopedia Jump to navigation Jump to search Free and open-source VPN protocol WireGuard is a communication protocol and free and open-source software that implements encrypted virtual private networks (VPNs), and was designed wi

en.wikipedia.org

 

https://www.wireguard.com/

 

WireGuard: fast, modern, secure VPN tunnel

WireGuard® is an extremely simple yet fast and modern VPN that utilizes state-of-the-art cryptography. It aims to be faster, simpler, leaner, and more useful than IPsec, while avoiding the massive headache. It intends to be considerably more performant th

www.wireguard.com

 

728x90
반응형
728x90
반응형

패키지 설치

sys와 subprocess를 활용하여 pip를 호출한다. 

아래 코드를 사용할 환경에 python과 pip가 설치되어 있고, 인터넷이 연결되어 있어야 작동한다.

 

import sys
import subprocess

try:
    # 없는 모듈 import시 에러 발생
    import pandas
except:
    # pip 모듈 업그레이드
    subprocess.check_call([sys.executable,'-m', 'pip', 'install', '--upgrade', 'pip'])
    # 에러 발생한 모듈 설치
    subprocess.check_call([sys.executable,'-m', 'pip', 'install', '--upgrade', 'pandas'])
    # 다시 import
    import pandas

 

728x90
반응형

'프로그래밍 > Python' 카테고리의 다른 글

[Python] 데코레이터 (@, Decorator)  (0) 2022.03.21
[Python] min, max 함수  (0) 2022.03.10
[python] lambda 표현식  (0) 2022.01.07
[Python] FinanceDataReader 모듈  (0) 2021.07.31
[Python] pykrx 모듈  (0) 2021.05.27
[Python] yfinance 모듈  (0) 2021.05.27
728x90
반응형

shift + 윈도우 + s

728x90
반응형
728x90
반응형

1. 소개 

https://parsec.app/

 

Connect to Work or Games from Anywhere | Parsec

Parsec is a remote desktop you'll actually love. Connect to work, games, or projects wherever you are, whenever you want.

parsec.app

- 계정을 생성하고 대상 PC와 Source PC에 동일한 계정으로 로그인 하면 P2P (UPNP) 연결을 통해 대상 PC의 화면을 로컬로 스트리밍

- 노트북, 스마트폰 등의 저성능 환경에서 대상 PC의 성능을 활용할 수 있음

  ex) 고성능 게임, 영상 작업, 음악 작업, AI 학습 등 작업 가능

 

2. 사용 가능한 환경

가능한 환경

728x90
반응형
728x90
반응형

1. 달팽이 배열

 - 외곽부터 정사각형을 채우고 대각선 아래로 이동하여 반복


 

2. 방법별 코드 정리

 2-1) 코드 

  - 외부부터 한바퀴씩 작성

  - 시계방향으로 회전하는 달팽이 배열을 이동 좌표를 미리 계산하는 방식으로 작성

# 범위내 좌표이동
def add_direction(x, y, arr_direction, int_direction, int_k):
    a, b = 0, 0
    
    # x 좌표 이동
    next_x = x + arr_direction[int_direction][0]
    if next_x >= 0 and next_x < int_k:
        a = next_x
    # y 좌표 이동
    next_y = y + arr_direction[int_direction][1]
    if next_y >= 0 and next_y < int_k:
        b = next_y
    
    return a, b

def snailArray_Generator(k):
    # k가 0보다 작거나 같으면 종료
    if k <= 0:
        return []

    # 이동할 좌표 구하기
    arr_Move = []
    # right, down, left, up
    arr_direction = [(1, 0), (0, 1), (-1, 0), (0, -1)]
    # 최초 시작 좌표
    x, y = 0, 0

    # 루프 한번에 한 바퀴
    for n in range(k-1, 0, -2):
        # 각 방향으로
        for int_direction in range(4):
            # n개 씩 채우기
            for _ in range(n):
                arr_Move.append((x, y))
                # 좌표 이동
                x, y = add_direction(x, y, arr_direction, int_direction, k)
        
        # 다음 시작 좌표로 이동
        x, y = x+1, y+1

    # 마지막 이동한 위치가 array에 이미 있으면 추가 안함
    if not (x, y) in arr_Move:
        arr_Move.append((x, y))

    # 값 넣기
    arr_map = [[0 for _ in range(k)] for _ in range(k)]
    value = 0
    for move in arr_Move:
        value += 1
        arr_map[move[1]][move[0]] = value

    return arr_map


# map 출력
for map in snailArray_Generator(0):
    print(map)

 

 2-1) 결과

728x90
반응형
728x90
반응형

1. 문제

https://programmers.co.kr/learn/courses/30/lessons/43163

 

코딩테스트 연습 - 단어 변환

두 개의 단어 begin, target과 단어의 집합 words가 있습니다. 아래와 같은 규칙을 이용하여 begin에서 target으로 변환하는 가장 짧은 변환 과정을 찾으려고 합니다. 1. 한 번에 한 개의 알파벳만 바꿀 수

programmers.co.kr

 

2. 코드

def dfs(begin, target, words, visited):
    str_end = target
    str_start = begin
    int_depth = 0
    arr_stack = [str_start]
    
    while arr_stack:
        str_top = arr_stack.pop()
        print(str_top)
        
        if str_top == target:
            return int_depth
        
        for i in range(len(words)):
            if visited[i] or words[i] == str_top:
                continue
        
            for _ in range(len(words[i])):
                count_tmp = 0
                for j in range(len(words[i])):
                    if [ch for ch in words[i]][j] == [ch for ch in str_top][j]:
                        count_tmp+=1 
                
                if (len(words[i])-1) == count_tmp:
                    visited[i] = True
                    
                    if words[i] != str_end:
                        arr_stack.append(words[i])
                    else:
                        return int_depth+1
                    break
                    
        int_depth += 1
            
            
def solution(begin, target, words):
    if target not in words:
        return 0
    
    visited = [False] * (len(words))
    print(words)
    return dfs(begin, target, words, visited)

 

3. 결과

테스트 결과

728x90
반응형
728x90
반응형

1. 문제
https://programmers.co.kr/learn/courses/30/lessons/42748

 

코딩테스트 연습 - K번째수

[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3]

programmers.co.kr

 

2. 코드

def solution(array, commands):
    answer = []
    
    for cmd in commands:
        answer.append((lambda i, j : sorted(array[i-1:j]))(cmd[0], cmd[1])[cmd[2]-1])
    
    return answer

 

3. 결과

728x90
반응형
728x90
반응형

1. 가설 적용 코드 (C++)

typedef unsigned long long ll;

/*
*  input : ll input (정수)
*  output : int (1 or 0)
*  unsigned long long 형태의 정수를 넣으면 해당 수가 소수인지 여부를 알려준다.
*  소수 판별 custom 버전
*/
int is_prime_number_custom(ll input)
{
    if (input < 2) {
        return 0;
    }

    for (ll j = 2; j <= (ll)(input / j); j++)
    {
        if (input % j == 0)
        {
            return 0;
        }
    }

    return 1;
}

 

2. 가설 적용 코드 (Python)

def func1(input):
    if input < 2:
    	return 0
    for j in range(2, int(input/j)+1):
        if input % j == 0:
            return 0
    return 1

 

3. 에라토스테네스의 체 (c++)

/*
* input : int m
* output : 1부터 m까지의 소수 여부를 sizeof(bool) * (m+1)크기의 bool * 형태로 반환한다.
* 사용 시 반환된 bool array에 해당 자연수를 조회하면 소수 여부를 알 수 있다.
*/
bool *Sieve_of_Eratosthenes(int m) {
    bool* arr = new bool[m + 1];

    memset(arr, 1, sizeof(bool) * (m+1));
    arr[0] = false;
    arr[0] = false;

    for (int i = 2; i < m + 1; i++) {
        if (arr[i] == true) {
            for (int j = i * 2; j < m + 1; j += i) {
                arr[j] = false;
            }
        }
    }

    return arr;
}

 

4. 최소 공배수, 최대 공약수

int func_2609_gcd(int a, int b) {
    if (a % b == 0) {
        return b;
    }
    else {
        return func_2609_gcd(b, a % b);
    }
}

int func_2609_lcm(int a, int b) {
    return (a * b) / func_2609_gcd(a, b);
}
728x90
반응형
728x90
반응형

1. 개요

 - 같은 라우터 내부에서 외부 인터넷이 제한되었으며, 파일을 공유해야할 때 작성하여 사용

 - 같은 공유기 내부의 사설 IP(Private IP)를 사용하여 TCP 소켓 스트림 방식으로 파일을 송수신함

 

2. 사용법

 - 원하는 경로에 File_Share.ps1, send.bat, recv.bat의 3개 파일을 위치시키고, 동일 위치에 전송할 대상을 send.zip으로 압축해 넣어둔다.

 - 파일을 받을 대상 PC에서 recv.bat을 실행 시키고  send.zip이 위치한 PC에서 send.bat을 실행한다.

 

3. 코드 (파워쉘 스크립트 작성)

# File_Share.ps1
param ( 
    [int] $sel = 1,
    [string] $IP = "127.0.0.1",
    [int] $Port = 29800,
    [String] $Send_FileName = "send.zip",
    [String] $Recv_FileName = "recv.zip"
) 

Function Recv_File {
    Param (
        [int] $Port = 29800,
        [String] $FileName = "recv.zip",
        [int] $ChunkSize = 1mb
    ) 

	# Socket Init
    $endpoint = new-object System.Net.IPEndPoint([ipaddress]::any, $port) 
    $listener = new-object System.Net.Sockets.TcpListener $endPoint
    $listener.start() 

    # 연결 대기
    $data = $listener.AcceptTcpClient() 

	# Stream 설정
    $socket_stream = $data.GetStream() 
    $FileReader = New-Object System.IO.BinaryReader $socket_stream
    $FileStream = [System.IO.FileStream]::new($FileName, [System.IO.FileMode]::Append, [System.IO.FileAccess]::Write)
    $Writer = New-Object System.IO.BinaryWriter($FileStream)

    for(){
        $Chunk = $FileReader.ReadBytes($ChunkSize)
        if($Chunk.Length){
            $Writer.Write($Chunk, 0, $Chunk.Length)
        }else{
            break
        }
    }
    
    # Close
    $Writer.Close()  
    $socket_stream.close()
    $listener.stop()
}

Function Send_File { 
    Param ( 
        [string] $IP = "127.0.0.1", 
        [int] $Port = 29800,
        [string] $FileName = "send.zip",
        [int] $ChunkSize = 1mb
    ) 
    
    # Setup connection 
    $EndPoint_IP = [System.Net.Dns]::GetHostAddresses($IP) 
    $Address = [System.Net.IPAddress]::Parse($EndPoint_IP) 
    $Socket = New-Object System.Net.Sockets.TCPClient($Address, $Port) 
    
    # stream 설정
    $Socket_Stream = $Socket.GetStream() 
    $Socket_Writer = New-Object System.IO.BinaryWriter($Socket_Stream)
    $FileInfo = Get-Item -LiteralPath $FileName
    $FileStream = $FileInfo.OpenRead()
    $FileReader = New-Object System.IO.BinaryReader $FileStream
    
    for() {
        $Chunk = $FileReader.ReadBytes($ChunkSize)
        $ChunkSum = 0
                    
        if($Chunk.Length) {
            $Socket_Writer.Write($Chunk, 0, $Chunk.Length)
            $ChunkSum += $Chunk.Length
        }else {
            Write-Host $ChunkSum 'Bytes 전송 완료'
            break;
        }
    }

    # Close
    $Socket_Writer.Close() 
    $FileReader.Close()
    $FileStream.Close()
    $Socket_Writer.Close()
    $Socket_Stream.Close()
}

if($sel -eq 1){
    Write-Host 'Listener'
    Recv_File -Port $Port -FileName $Recv_FileName
}else{
    Write-Host 'Sender'
    Send_File -IP $IP -Port $Port -FileName $Send_FileName
}

 

4. 코드(배치파일 작성)

// listener Start
// recv.bat
#echo off

powershell.exe -File File_Share.ps1 -sel 1

pause
// sender Start
// send.bat
#echo off

powershell.exe -File File_Share.ps1 -sel 2 -IP 127.0.0.1

pause
728x90
반응형

+ Recent posts