結果

問題 No.526 フィボナッチ数列の第N項をMで割った余りを求める
ユーザー r6ever6eve
提出日時 2017-08-17 16:43:23
言語 OCaml
(5.1.0)
結果
AC  
実行時間 2 ms / 2,000 ms
コード長 799 bytes
コンパイル時間 234 ms
コンパイル使用メモリ 21,660 KB
実行使用メモリ 6,948 KB
最終ジャッジ日時 2024-04-17 08:42:43
合計ジャッジ時間 814 ms
ジャッジサーバーID
(参考情報)
judge4 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
6,816 KB
testcase_01 AC 2 ms
6,940 KB
testcase_02 AC 2 ms
6,940 KB
testcase_03 AC 2 ms
6,940 KB
testcase_04 AC 2 ms
6,940 KB
testcase_05 AC 2 ms
6,944 KB
testcase_06 AC 2 ms
6,940 KB
testcase_07 AC 2 ms
6,940 KB
testcase_08 AC 2 ms
6,940 KB
testcase_09 AC 2 ms
6,940 KB
testcase_10 AC 2 ms
6,940 KB
testcase_11 AC 2 ms
6,944 KB
testcase_12 AC 2 ms
6,940 KB
testcase_13 AC 2 ms
6,940 KB
testcase_14 AC 1 ms
6,948 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

let mul a b m =
  let na0 = Array.length a in
  let nb0 = Array.length b in
  let nb1 = Array.length b.(0) in
  let c = Array.make_matrix na0 nb1 0 in
  for i = 0 to na0 - 1 do
    for k = 0 to nb0 - 1 do
      for j = 0 to nb1 - 1 do
        c.(i).(j) <- (c.(i).(j) + a.(i).(k) * b.(k).(j)) mod m
      done
    done
  done;
  c


let fib (n, m) =
  let a = Array.make_matrix 2 2 0 in
  a.(0).(0) <- 1; a.(0).(1) <- 1;
  a.(1).(0) <- 1; a.(1).(1) <- 0;
  let b = Array.make_matrix 2 2 0 in
  b.(0).(0) <- 1; b.(0).(1) <- 0;
  b.(1).(0) <- 0; b.(1).(1) <- 1;
  let rec doit n a b =
    if n = 0 then b
    else doit (n / 2) (mul a a m) (if n mod 2 = 0 then b else mul b a m) in
  let c = doit (n - 1) a b in
  c.(1).(0)

let () = Scanf.scanf "%d %d " (fun n m -> n, m) |> fib |> Printf.printf "%d\n"
0