분산처리


백준 [1009] 분산처리

문제보기
Alt text

풀이

제곱근은 끝자리가 반복됨을 이용한다.
e.g. 2^8 : 2 , 4 , 8 , 16, 32, 64, 128, 256 => 끝자리는 2, 4, 8, 6 이 반복된다.
반복되는 규칙을 찾는것으로 구현했지만, 2~9까지 배열로 미리 담아두는 방법도 있다

소스코드

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int T = sc.nextInt();
        for (int tc = 0; tc < T; tc++) {
            int a = sc.nextInt();
            int b = sc.nextInt();

            if (a == 1) {
                System.out.println(a);
                continue;
            }

            List<Integer> rule = findRule(a, b);
            System.out.println(findComputerNum(rule, b));
        }
    }

    private static List<Integer> findRule(int a, int b) {
        List<Integer> rule = new ArrayList<>();

        BigInteger beforeValue = BigInteger.valueOf(a);
        for (int i = 1; i <= b; i++) {
            BigInteger value = beforeValue.pow(i);
            int lastNum = value.mod(BigInteger.valueOf(10)).intValue();

            if (rule.contains(lastNum)) {
                break;
            } else {
                rule.add(lastNum);
            }
        }

        return rule;
    }

    private static int findComputerNum(List<Integer> rule, int b) {
        int ruleSize = rule.size();
        int ruleIdx;

        // 마지막 숫자의 끝자리 확인
        int theLast = b % ruleSize;
        if (theLast == 0) {
            ruleIdx = ruleSize - 1;
        } else {
            ruleIdx = theLast - 1;
        }

        // 끝자리가 0이라면 컴퓨터 번호는 10
        int result = rule.get(ruleIdx);
        if (result == 0) result = 10;

        return result;
    }
}