본문 바로가기

코딩/알고리즘

[C#] 백준 2749 피보나치수 3

using System; using System.Collections.Generic; namespace CsharpConsoleApplication { class Matrix { public static int mod = 1000000; public long[,] mat = new long[2,2]; public void setMat(long i0, long i1, long j0, long j1) { mat[0,0] = i0; mat[0,1] = i1; mat[1,0] = j0; mat[1,1] = j1; } public Matrix(long i0, long i1, long j0, long j1) { setMat(i0, i1, j0, j1); } public static Matrix operator*(Matrix leftM, Matrix rightM) { long m00, m01, m10, m11; m00 = (leftM.mat[0, 0] * rightM.mat[0, 0] % mod + leftM.mat[0, 1] * rightM.mat[1, 0] % mod) % mod; m01 = (leftM.mat[0, 0] * rightM.mat[0, 1] % mod + leftM.mat[0, 1] * rightM.mat[1, 1] % mod) % mod; m10 = (leftM.mat[1, 0] * rightM.mat[0, 0] % mod + leftM.mat[1, 1] * rightM.mat[1, 0] % mod) % mod; m11 = (leftM.mat[1, 0] * rightM.mat[0, 1] % mod + leftM.mat[1, 1] * rightM.mat[1, 1] % mod) % mod; return new Matrix(m00, m01, m10, m11); } public override string ToString() { return "[ " + mat[0, 0] + " " + mat[0, 1] + " ]\n[ " + mat[1, 0] + " " + mat[1, 1] + " ]\n"; } } class Program { static List<Matrix> pibMat = new List<Matrix>(); static void Main(string[] args) { long n; n = Int64.Parse(Console.ReadLine()); pibMat.Add(new Matrix(1, 1, 1, 0)); for(int i = 0; i < 65; i++) { pibMat.Add(pibMat[i] * pibMat[i]); } Matrix resultMat = new Matrix(1, 0, 0, 1); long one = 1; int j = 0; while (n >= 1) { long a = one & n; if (a == 1) { resultMat = resultMat * pibMat[j]; } n = n >> 1; j++; } Console.WriteLine(resultMat.mat[0,1]); } } }




오랜만에 C#으로 만들었다.

'코딩 > 알고리즘' 카테고리의 다른 글

백준 1780 종이의 개수  (0) 2017.06.04
백준 11004 K번째 수  (0) 2017.06.02
백준 9252 LCS2  (0) 2017.05.27
백준 1932 숫자삼각형  (0) 2017.05.27
백준 9461 파도반수열  (0) 2017.05.27