작성일 :

문제 링크

8559번 - Potęga

설명

2^n의 일의 자리 숫자를 구하는 문제입니다.


접근법

2의 거듭제곱의 일의 자리는 2, 4, 8, 6이 반복됩니다. 따라서 n4로 나눈 나머지만 알면 답을 정할 수 있습니다.

다만 n이 매우 클 수 있으므로 정수형으로 읽지 않고 문자열로 받습니다. 문자열을 한 자리씩 보면서 4로 나눈 나머지를 구한 뒤, 그 값에 맞는 일의 자리 숫자를 출력하면 됩니다. n = 0일 때는 2^0 = 1이므로 따로 처리합니다.



Code

C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;

class Program {
  static void Main() {
    string n = Console.ReadLine()!;

    if (n == "0") {
      Console.WriteLine(1);
      return;
    }

    int mod = 0;
    for (int i = 0; i < n.Length; i++) {
      mod = (mod * 10 + (n[i] - '0')) % 4;
    }

    if (mod == 1)
      Console.WriteLine(2);
    else if (mod == 2)
      Console.WriteLine(4);
    else if (mod == 3)
      Console.WriteLine(8);
    else
      Console.WriteLine(6);
  }
}

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <bits/stdc++.h>
using namespace std;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  string n;
  cin >> n;

  if (n == "0") {
    cout << 1 << "\n";
    return 0;
  }

  int mod = 0;
  for (char ch : n) {
    mod = (mod * 10 + (ch - '0')) % 4;
  }

  if (mod == 1)
    cout << 2 << "\n";
  else if (mod == 2)
    cout << 4 << "\n";
  else if (mod == 3)
    cout << 8 << "\n";
  else
    cout << 6 << "\n";

  return 0;
}

Tags: 8559, BOJ, C#, C++, 백준, 수학, 알고리즘

Categories: ,