0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CodeIQ「『トライアングル・メイズ』問題」に参加しました。

Last updated at Posted at 2016-10-01

CodeIQ「『トライアングル・メイズ』問題」の掲載期間が終了したということで、自分が提出したコード(Python3)を公開します。ほかの解答者のコードはTogetterにまとめらていますので、そちらもぜひ。


"""
「『トライアングル・メイズ』問題」の解答コード。

1. 漸化式はF(n + 1) = F(n) * (F(n) + 1)
2. F(n) mod 1000003, F(n + 1) mod 1000003, ... が「繰り返し」を持つことを利用する
"""

if __name__ == '__main__':
    ls = [0, 1]
    ht = {}

    # n=0からF(n)の値を探索しlsに記録する。
    # 「繰り返し」が現れた時点で探索を終了してもよい。
    for i in range(2, 10000003):
        t = (ls[-1] * ls[-1] + ls[-1]) % 1000003
        if t in ht: break

        ls.append(t)
        ht[t] = i
    
    # 「繰り返し」の開始地点と終了地点を探す
    start = ht[(ls[-1] * ls[-1] + ls[-1]) % 1000003]
    end = len(ls) - 1

    # F(n)の値を計算し、出力する。
    n = int(input())
    if end < n: n = (n - start) % (end + 1 - start) + start
    
    print(ls[n])

さて感想ですが、漸化式$F(n + 1) = F(n) * (F(n) + 1)$と「繰り返し」のふたつに気がつけば溶ける問題だったように思います。漸化式についてはシンプルで気が付きやすいものでしたし、サンプルに挙げられた値をGoogle検索すればOEISがヒットした記憶もあります(肝心のページは失念)。また「100003でわったあまりを求めなさい」という指示から「繰り返し」も連想しやすかったと思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?