如何进行时间分析

问题描述

我必须为使用循环计算从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.
}