본문 바로가기
문제풀이/코드업

코드업 기초 100제 C++/Java (78~92)

by 혀니쌤1 2023. 12. 21.

목차

    코드업 78번 부터는 기초 종합이다. 지금까지 배웠던 것을 사용해서 다양한 문제 풀이를 해볼 수 있다.

    78번~92번 : 기초 종합 (배열X)

     

    #1078

    #include <iostream>
    int main() {
    	int a;
    	std::cin >> a;
    	int res = 0;
    	for (int i = 2; i <= a; i++) {
    		if (i % 2 == 0) {
    			res += i;
    		}
    	}
    	std::cout << res;
    	return 0;
    }

    import java.util.Scanner;
    public class Main{
    	public static void main(String arg[]) {
    		Scanner sc = new Scanner(System.in);
    		int a = sc.nextInt();
    		int sum = 0;
    		for (int ii=0; ii<=a; ii+=2) {
    			sum+=ii;
    		}
    		System.out.println(sum);
    	}
    }

     

    #1079

    #include <iostream>
    int main() {
    	char c;
    	while (1) {
    		std::cin >> c;
    		std::cout << c << std::endl;
    		if (c == 'q') {
    			break;
    		}
    	}
    	return 0;
    }

    import java.util.StringTokenizer;
    import java.util.Scanner;
    
    public class Main {
    	public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
    		StringTokenizer st = new StringTokenizer(sc.nextLine()," ");
    		char c; 
    		while (true) {
    			c = st.nextToken().charAt(0);
    			System.out.println(c);
    			if (c == 'q') {
    				break;
    			}
    		}
    	}
    
    }

     

    #1080

    #include <iostream>
    int main() {
    	int a;
    	std::cin >> a;
    	int res = 0;
    	for (int i = 2; i <= a; i++) {
    		if (i % 2 == 0) {
    			res += i;
    		}
    	}
    	std::cout << res;
    	return 0;
    }

    import java.util.Scanner;
    public class Main{
    	public static void main(String arg[]) {
    		Scanner sc = new Scanner(System.in);
    		int a = sc.nextInt();
    		int sum = 0;
    		for (int ii=0; ii<=a; ii+=2) {
    			sum+=ii;
    		}
    		System.out.println(sum);
    	}
    }

     

    #1081

    #include <iostream>
    int main() {
    	int a, b;
    	std::cin >> a >> b;
    	for (int i = 1; i <= a; i++) {
    		for (int j = 1; j <= b; j++) {
    			std::cout << i << " " << j << std::endl;
    		}
    	}
    	return 0;
    }

    import java.util.Scanner;
    public class Main{
    	public static void main(String args[]) {
    		Scanner sc = new Scanner(System.in);
    		int n1 = sc.nextInt();
    		int n2 = sc.nextInt();
    		for (int ii=1;ii<=n1;ii++) {
    			for (int jj=1;jj<=n2;jj++) {
    				System.out.format("%d %d\n",ii,jj);
    			}
    		}
    	}
    }

     

    #1082

    #include <iostream>
    int main() {
    	char c;
    	std::cin >> c;
    	for (int i = 1; i <= 15; i++) {
    		int a = ((int)c - 55) * i;
    		printf("%c*%X=%X\n",c,i,a);
    	}
    	return 0;
    }

    import java.util.Scanner;
    public class Main{
    	public static void main(String args[]) {
    		Scanner sc = new Scanner(System.in);
    		String s = sc.next();
            int a = Integer.parseInt(s, 16);
    		for (int ii = 1; ii <= 15; ii++) {
    		    String s1 = Integer.toHexString(ii).toUpperCase();
    		    String s2 = Integer.toHexString(a*ii).toUpperCase();
    			System.out.format("%s*%s=%s\n", s, s1, s2);
    		}
    	}
    }

     

    #1083

    숫자가 1~10까지만 나온다는 것을 고려하면 아주 쉬운 문제였다. 처음엔 문제를 제대로 읽지 않아 진짜 369 게임을 만들어야하는 줄 알았다. 예를 들면 33이 들어오면 XX라고 외치는 식이다. 그러면 풀이가 더 복잡해지만, 이 문제에선 그렇게 까지 필요 없다.

    #include <iostream>
    using namespace std;
    
    int main() {
    	int i;
    	std::cin >> i;
    	for (int j = 1; j <= i; j++) {
    		if (j % 3 == 0) {
    			cout << "X ";
    		}
    		else {
    			cout << j << " ";
    		}
    	}
    	return 0;
    }

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int a = sc.nextInt();
            StringBuilder stb = new StringBuilder();
            for (int i = 1; i <= a; i++) {
                if (i % 3 == 0) {
                    stb.append("X ");
                } else {
                    stb.append(i + " ");
                }
            }
            System.out.println(stb);
        }
    }

     

     

    자바의 경우 버퍼 사용을 해보자

    #1084

    #include <iostream>
    using namespace std;
    
    int main() {
    	int r, g, b;
    	int cnt = 0;
    	cin >> r >> g >> b;
    	for (int i = 0; i < r; i++) {
    		for (int j = 0; j < g; j++) {
    			for (int k = 0; k < b; k++) {
    				printf("%d %d %d\n", i, j, k);
    				cnt++;
    			}
    		}
    	}
    	cout << cnt;
    	return 0;
    }

    #BufferWriter가 꼭 필요할 때!

    자바의 경우 BufferedWriter를 사용해야지만 메모리초과/시간초과 등이 나지 않는다. for loop이 3겹이나 되다 보니 숫자가 커질 수록 경우의 수가 커져서 *쓰기* 시간을 줄이는 것이 중요했나보다. *읽기*의 경우 딱 숫자 3개만 읽으면 되어서 스캐너만 써도 충분하다.

    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.util.Scanner;
    
    public class Main {
    
        public static void main(String[] args) throws IOException {
            Scanner sc = new Scanner(System.in);
            int r = sc.nextInt();
            int g = sc.nextInt();
            int b = sc.nextInt();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
            for (int i = 0; i < r; i++) {
                for (int j = 0; j < g; j++) {
                    for (int k = 0; k < b; k++) {
                        bw.write(i + " " + j + " " + k + "\n");
                    }
                }
            }
            bw.write(String.valueOf(r * g * b));
            bw.flush();
            bw.close();
        }
    }

    아래는 주어진 예제는 맞지만, 실제 제출하면 메모리 초과가 뜨는 코드다.

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int r = sc.nextInt();
            int g = sc.nextInt();
            int b = sc.nextInt();
    
            for (int i = 0; i < r; i++) {
                for (int j = 0; j < g; j++) {
                    for (int k = 0; k < b; k++) {
                        System.out.format("%d %d %d\n", i, j, k);
                    }
                }
            }
            System.out.println(r * g * b);
        }
    }

     

    #1085

    #include <iostream>
    using namespace std;
    
    int main() {
    	int h, b, c, s;
    	scanf("%d %d %d %d\n", &h, &b, &c, &s);
    	printf("%.1f MB", (float) h * b * c * s / 8 / 1024 / 1024);
    	return 0;
    }

    import java.io.IOException;
    import java.util.Scanner;
    
    public class Main {
    
        public static void main(String[] args) throws IOException {
            Scanner sc = new Scanner(System.in);
            int a = sc.nextInt();
            int b = sc.nextInt();
            int c = sc.nextInt();
            int d = sc.nextInt();
            long e = (long) a * b * c * d;
            System.out.printf("%.1f MB", e / (8.0 * 1024 * 1024));
        }
    }

     

    #1086

    1085랑 아주 유사한 문제다. 

    #include <iostream>
    using namespace std;
    
    int main() {
    	int w, h, b;
    	scanf("%d %d %d\n", &w, &h, &b);
    	printf("%.2f MB", (float) w * h * b / 8 / 1024 / 1024);
    	return 0;
    }

    import java.util.Scanner;
    
    public class Main {
    
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int a = sc.nextInt();
            int b = sc.nextInt();
            int c = sc.nextInt();
            long e = (long) a * b * c;
            System.out.printf("%.2f MB", e / (8.0 * 1024 * 1024));
        }
    }

     

    #1087

    #include <iostream>
    using namespace std;
    
    int main() {
    	int i = 1;
    	int cur = 0;
    	int target;
    	cin >> target;
    	while (cur < target) {
    		cur += i++;
    	}
    	cout << cur;
    	return 0;
    }

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int a = sc.nextInt();
            int b = 0;
            int add = 0;
            while (true) {
                b += ++add;
                if (b >= a) {
                    System.out.println(b);
                    break;
                }
            }
        }
    }

     

    #1088

    #include <iostream>
    using namespace std;
    
    int main() {
    	int i;
    	cin >> i;
    	for (int j = 1; j <= i; j++) {
    		if (j % 3 != 0) {
    			cout << j << " ";
    		}
    	}
    	return 0;
    }

    #BufferReader는 굳이...

    1088같은 문제야 말로 출력량이 많기 때문에 버퍼를 쓰면 좋다. 하지만 입력은 Scanner가 낫다. 굳이 BufferedReader를 쓸 필요가 없다. (Scanner가 사실 사용하기엔 훨씬 쉽지 않은가) 

    // 출력은 버퍼, 입력은 스캐너
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.util.Scanner;
    
    public class Main {
    
        public static void main(String[] args) throws IOException {
            Scanner sc = new Scanner(System.in);
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
            int a = sc.nextInt();
            for (int ii = 1; ii <= a; ii++) {
                if (ii % 3 != 0) {
                    bw.write(String.format("%d ", ii));
                }
            }
            bw.flush();
            bw.close();
        }
    
    }

     

    // 출력 입력 모두 버퍼
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    
    public class Main {
    
        public static void main(String[] args) throws IOException{
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
            int a = Integer.parseInt(br.readLine());
            for (int ii=1;ii<=a;ii++) {
                if (ii%3!=0) {
                    bw.write(String.format("%d ", ii));
                }
            }
            br.close();
            bw.flush();
            bw.close();
        }
    
    }

    아래 사진을 보면 시간상 거의 차이가 없다.

     

    #1089

    #include <iostream>
    using namespace std;
    
    int main() {
    	int a, d, n;
    	cin >> a >> d >> n;
    	cout << a + d * (n - 1);
    	return 0;
    }

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int a = sc.nextInt();
            int b = sc.nextInt();
            int c = sc.nextInt();
            System.out.println((long) a + (long) b * (c - 1));
        }
    }

     

    #1090

    #include <iostream>
    using namespace std;
    
    int main() {
    	long long a, d, n;
    	cin >> a >> d >> n;
    	for (int i = 0; i < n-1; i++) {
    		a *= d;
    	}
    	cout << a;
    	return 0;
    }

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            long a = sc.nextInt();
            int d = sc.nextInt();
            int n = sc.nextInt();
            for (int i = 0; i < n - 1; i++) {
                a *= d;
            }
            System.out.println(a);
        }
    }

     

    #1091

    #include <iostream>
    using namespace std;
    
    int main() {
    	long long a;
    	int b, c, d;
    	cin >> a >> b >> c >> d;
    	for (int i = 0; i < d - 1; i++) {
    		a = a * b + c;
    	}
    	cout << a;
    	return 0;
    }

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            long a = sc.nextLong();
            int b = sc.nextInt();
            int c = sc.nextInt();
            int d = sc.nextInt();
            for (int ii = 1; ii < d; ii++) {
                a = a * b + c;
            }
            System.out.println(a);
        }
    }

     

    #유클리드호제법?

    #1092

    최소공배수 (LCM, Least Common Multiplier) 를 구하는 문제였다. 사실 최대 숫자 조건이 100이하로 크지 않아서 while로 써도 간단히 풀린다. 하지만 만약 숫자가 커진다면? 그 때는 유클리드호제법 등의 기법을 써야 시간 초과가 나지 않을 것이다. 사실 C++는 빠른 언어기 때문에 유클리드 호제법을 쓰던 안 쓰던 모두 0초가 뜨긴 했다. (이번 문제에서는)

    //Simply WHILE. Euclidean algorithm NOT USED
    
    #include <iostream>
    using namespace std;
    
    int main() {
      int a, b, c, i;
      cin >> a >> b >> c;
      i = 1;
      while (true) {
        if (i % a == 0 && i % b == 0 && i % c == 0) {
          cout << i;
          break;
        }
        i += 1;
      }
      return 0;
    }

     

    //Euclidean algorithm USED
    
    #include <iostream>
    using namespace std;
    
    int gcd(int num1, int num2) {
        while (num1 != num2) {
            if (num1 > num2)
                num1 -= num2;
            else
                num2 -= num1;
        }
        return num1;
    }
    
    int lcm(int num1, int num2) {
        return (num1 / gcd(num1, num2)) * num2;
    }
    
    int main() {
    	int a, b, c;
    	int ans;
    	cin >> a >> b >> c;
        cout << lcm(lcm(a, b), c);
    	return 0;
    }

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int a = sc.nextInt();
            int b = sc.nextInt();
            int c = sc.nextInt();
            int answer = 0;
            while (true) {
                answer++;
                if (answer % a == 0 && answer % b == 0 && answer % c == 0) {
                    break;
                }
            }
            System.out.println(answer);
        }
    }

     

     

    예전 글 정리

     

    코드업 기초 100제 C++/Java (1~37)

    1~8번: 기초 출력 스탠다드 인풋 없이 스탠다드 아웃풋만 내는 방식이다. C++의 경우 cout을 사용하였다. (물론 printf도 가능은 하지만) using namespace std;를 외치지 않은 경우, 그냥 cout이 아니라 std::cou

    mylittlenotepad.tistory.com

     

    코드업 기초 100제 C++/Java (38~46, 49~58, 63~64)

    문제집 / C언어 기초 100제 codeup.kr 코드업 기초 100제 C++/Java (1~37) 1~8번: 기초 출력 스탠다드 인풋 없이 스탠다드 아웃풋만 내는 방식이다. C++의 경우 cout을 사용하였다. (물론 printf도 가능은 하지만

    mylittlenotepad.tistory.com

     

    코드업 기초 100제 C++/Java (65~77)

    문제집 / C언어 기초 100제 codeup.kr 코드업 기초 100제 C++/Java (1~37) 1~8번: 기초 출력 스탠다드 인풋 없이 스탠다드 아웃풋만 내는 방식이다. C++의 경우 cout을 사용하였다. (물론 printf도 가능은 하지만

    mylittlenotepad.tistory.com