如何进行时间分析

How to Time Analysis

我不得不为一个函数编写代码,该函数使用循环来计算从 1 到 n 的所有整数的总和。 我还需要做一个时间分析,把每个基本操作(比如赋值和++)算作一个操作。我需要帮助来理解如何计算每个基本操作。 int computeSume(int n) 是不是一步,也就是C1? for循环是多步? 请帮忙解释一下。谢谢。

#include <iostream>

using namespace std;

//Create a function that uses a loop to compute the sum of all integers from 1 to n.

//Create Function
int computeSum(int n)
{
    //create sum variable
    int sum = 0;
    
    //create for loop
    // i must be <= to n so it will count all integers and not cut the last int off.
    for (int i = 0; i <= n; i++)
    {
        sum = sum + i;
    }
        //return statement
        return sum;
}

//Main Method
int main()
{
    //Input varibale
    int n;
    
    //Create user prompt
    cout << "Enter a value: " << endl;
    cin >> n;
    cout << "The sum of all integer from 1 to " << n << " is " << computeSum(n) << "." << endl;
    
    return 0;
}

看看这个和平,我把必要的信息都注释掉了,供大家参考。

#include <iostream>

using namespace std;

int computeSum(int n)
{
    int sum = 0;        // One unit time.
    
    
    for (int i = 0; i <= n; i++)        // Condition will be checked N+1 times so n+1 unit time.
    {
        sum = sum + i;
    }
        
    return sum;     // One unit time.

    // Total units of time is N+3, which is nothing but O(N).
}

//Main Method
int main()
{
    
    int n;          // Declaring a variable is one unit time.
    
    cout << "Enter a value: " << endl;      // One unit time.
    cin >> n;           // Depends how much time you take to enter value, But for simplicity taking as 1 unit.
    cout << "The sum of all integer from 1 to " << n << " is " << computeSum(n) << "." << endl;     // It could have been taken only a simple statement with one unit time.
                                                                                                    // But computeSum(n) is a function so, we first analyse it's time.
    
    return 0;       // one unit.
}