【问题标题】:How to Time Analysis如何进行时间分析
【发布时间】:2020-12-11 02:52:58
【问题描述】:

我必须为一个函数编写代码,该函数使用循环来计算从 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;
}

【问题讨论】:

  • int op_count = 0;每次做基本操作,就做++op_count;
  • std::accumulate

标签: c++ time analysis


【解决方案1】:

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

#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.
}

【讨论】:

  • 不完全正确。如果您分解for 循环,您会注意到它有一个赋值操作(对于i=0),并且对于每一步i 都会递增。这不会修改最终答案(确实是 O(n)),但根据问题,您的分析缺少一些考虑因素。
  • 是的,你是对的,但是,我试图让它简单易懂,因为在决赛中我们只需要计算我们的程序所花费的时间顺序。
  • 谢谢,这很有帮助。我知道答案必须是 O(n),但我不确定你如何计算 for 循环。
猜你喜欢
  • 2012-06-05
  • 2022-01-14
  • 2019-07-03
  • 2013-08-14
  • 2017-05-12
  • 2021-09-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多