본문 바로가기
Problem Solving/Baekjoon

[백준] 9471 피사노 주기 - Brute Force / Java

by graycode 2023. 10. 1.

 문제 링크

 

9471번: 피사노 주기

첫째 줄에 테스트 케이스의 개수 P가 주어진다. 각 테스트 케이스는 N과 M으로 이루어져 있다. N은 테스트 케이스의 번호이고, M은 문제에서 설명한 m이다.

www.acmicpc.net

 

 풀이 코드

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        StringBuilder sb = new StringBuilder();

        int p = read();
        while (p-- > 0) {
            int n = read(), m = read(), a = 0, b = 1, cnt = 0;

            do {
                int tmp = (a + b) % m;
                a = b;
                b = tmp;
                cnt++;
            } while (a != 0 || b != 1);

            sb.append(n).append(" ").append(cnt).append("\n");
        }

        bw.write(sb.toString());
        bw.flush();
    }

    private static int read() throws IOException {
        int c, n = System.in.read() & 15;
        while ((c = System.in.read()) > 32) n = (n << 3) + (n << 1) + (c & 15);

        return n;
    }

}

댓글