このプロンプトを開発者向けコンソールにコピーして、自分で試してみましょう!

内容
Systemあなたの任務は、提供された関数やアルゴリズムを分析し、ビッグO記法を使用してその時間計算量を計算することです。ステップバイステップで推論を説明し、最終的な時間計算量にどのようにたどり着いたかを説明してください。時間計算量を決定する際には、最悪のケースシナリオを考慮してください。関数やアルゴリズムに複数のステップやネストされたループが含まれている場合は、各ステップの時間計算量を提供し、その後、関数やアルゴリズム全体の全体的な時間計算量を示してください。特に指定がない限り、使用されている組み込み関数や操作の時間計算量はO(1)と仮定してください。
Userdef example_function(n): for i in range(n): print(i) for j in range(n): for k in range(n): print(j, k)

出力例

与えられた関数example_function(n)の時間計算量を分析するために、ステップごとに分解し、最悪のケースシナリオを考慮します。

ステップ1:最初のループの分析

for i in range(n):
   print(i)

このループはn回繰り返され、各繰り返しで定数時間の操作(print(i))を実行します。したがって、このステップの時間計算量はO(n)です。

ステップ2:ネストされたループの分析

for j in range(n):
    for k in range(n):
        print(j, k)

外側のループはn回繰り返され、各繰り返しごとに内側のループもn回繰り返されます。内側のループの各繰り返しでは、定数時間の操作(print(j, k))が実行されます。したがって、ネストされたループの時間計算量はO(n * n) = O(n^2)です。

ステップ3:時間計算量の組み合わせ
関数example_function(n)は2つのステップで構成されています:最初のループとネストされたループです。全体の時間計算量は、各ステップの時間計算量の合計です。

最初のループの時間計算量:O(n)
ネストされたループの時間計算量:O(n^2)

全体の時間計算量を決定するために、成長の次数が最も高い支配的な項を考慮します。この場合、O(n^2)がO(n)を支配します。

したがって、関数example_function(n)の全体的な時間計算量はO(n^2)です。

最悪のケースシナリオでは、nが大きい場合、ネストされたループが実行時間を支配し、関数は二次の時間計算量を持ちます。


APIリクエスト

import anthropic

client = anthropic.Anthropic(
    # defaults to os.environ.get("ANTHROPIC_API_KEY")
    api_key="my_api_key",
)
message = client.messages.create(
    model="claude-opus-4-20250514",
    max_tokens=1000,
    temperature=0,
    system="Your task is to analyze the provided function or algorithm and calculate its time complexity using Big O notation. Explain your reasoning step by step, describing how you arrived at the final time complexity. Consider the worst-case scenario when determining the time complexity. If the function or algorithm contains multiple steps or nested loops, provide the time complexity for each step and then give the overall time complexity for the entire function or algorithm. Assume any built-in functions or operations used have a time complexity of O(1) unless otherwise specified.",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "def example_function(n):\n    for i in range(n):\n        print(i)\n\n    for j in range(n):\n        for k in range(n):\n            print(j, k)"
                }
            ]
        }
    ]
)
print(message.content)