結果

問題 No.303 割れません
ユーザー Min_25
提出日時 2015-11-14 07:33:02
言語 PyPy2
(7.3.15)
結果
AC  
実行時間 867 ms / 10,000 ms
コード長 2,343 bytes
コンパイル時間 231 ms
コンパイル使用メモリ 76,808 KB
実行使用メモリ 103,356 KB
最終ジャッジ日時 2024-09-13 16:41:45
合計ジャッジ時間 9,421 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 14
権限があれば一括ダウンロードができます

ソースコード

diff #

def fib(n):
  if n <= 2:
    return ((n + 1) >> 1, (n + 2) >> 1)
  a, b = fib(n >> 1)
  if n & 1:
    return (a * a + b * b, b * ((a << 1) + b))
  else:
    return (a * ((b << 1) - a), a * a + b * b)

def fast_divmod(N, D, threshold=1<<512):
  i_prec = 50

  if N < threshold or D < (1 << i_prec):
    return divmod(N, D)

  if N < D:
    return (0, N)

  guard_bits = 3

  ilog2_n = N.bit_length()
  ilog2_d = D.bit_length()
  ilog2_q = ilog2_n + 1 - ilog2_d

  n_shamt = ilog2_n - (ilog2_q + guard_bits)

  d = D >> (ilog2_d - i_prec)
  reciprocal = int(float(1 << (2 * i_prec)) / float(d))

  prec = ilog2_q
  precs = []
  while prec > i_prec:
    precs.append(prec)
    prec = (prec >> 1) + guard_bits

  curr_prec = i_prec
  for prec in precs[::-1]:
    if prec >= ilog2_d:
      d = D
      lshift = prec - ilog2_d
    else:
      d = D >> (ilog2_d - prec)
      lshift = 0
    r = (1 << prec) - (((d * reciprocal) << lshift) >> curr_prec)
    left = reciprocal << (prec - curr_prec)
    right = (reciprocal * r) >> curr_prec
    reciprocal = left + right
    curr_prec = prec

  n = N >> n_shamt
  q = (n * reciprocal) >> (curr_prec + guard_bits + 1)
  r = N - q * D

  if r < 0:
    while r < 0:
      r += D
      q -= 1
  elif r >= D:
    while r >= D:
      r -= D
      q += 1
  return q, r

def print_big_integer(N, out, newline=True, beg=0, tens=None):
  def rec(N, e, zerofill=False):
    if e <= 10:
      if not zerofill:
        out.write("%s" % str(N)[beg:])
      else:
        out.write("%0*d" % (1 << e, N))
    else:
      ten = tens[e-1]
      q, r = fast_divmod(N, ten)
      if zerofill or q:
        rec(q, e - 1, zerofill)
        rec(r, e - 1, True)
      else:
        rec(r, e - 1, zerofill)

  if N < 0:
    N = -N
    out.write("-")

  if tens is None:
    tens = []
    ten = 10
    while ten <= N:
      tens.append(ten)
      if ten.bit_length() * 2 - 1 > N.bit_length():
        break
      ten *= ten

  e = 0
  while e < len(tens) and N >= tens[e]:
    e += 1

  rec(N, e)

  if newline:
    print("")

  return

def prob303():
  import sys
  n = int(sys.stdin.readline())
  if n == 2:
    print("3")
    print("INF")
  else:
    if n & 1:
      ans = fib(n)[0]
    else:
      a, b = fib(n // 2 - 1)
      ans = (a * b) << 1
    print(n)
#   print(ans)
    print_big_integer(ans, sys.stdout)

prob303()
0