Algorithm, Data structure/Solved Algorithmic Problem

BAEKJOON 1009 - 분산처리

JaykayChoi 2016. 7. 23. 18:18

문제: https://www.acmicpc.net/problem/1009


a 의 b 승의 마지막 자리의 값을 구하는 문제입니다. 우선 b가 최대 1,000,000 이기 때문에 모든 값을 저장할 수 없으므로 마지막 자리의 값만 남겨두어 계산을 하고 실제로 0~9를 제곱하다보면 최대 4개의 패턴으로 묶이는 것을 확인할 수 있습니다. 이 점을 이용해 시간복잡도를 줄일 수 있습니다.



my solving

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
32
33
34
35
36
37
38
#include <fstream>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
 
int main()
{
    int cases;
    cin >> cases;
    for (int i = 0; i < cases; i++)
    {
        int a, b;
        cin >> a >> b;
 
        string str = to_string(a);
        a = str[str.size() - 1- '0';
 
        b--;
        b %= 4;
        int ret = a;
        for (int j = 0; j < b; j++)
        {
            ret *= a;
            str = to_string(ret);
            ret = str[str.size() - 1- '0';
            if (ret == 0)
                break;
        }
        if (ret == 0)
            cout << 10 << endl;
        else
            cout << ret << endl;
    }
 
    return 0;
}
 
cs