我对下面代码片段中的操作总数的想法是否有效? (大 O 符号)

Is my thinking for the total number of operations in the code-snippet below valid? (Big-O notation)

public class foo{   
    public static void main(String[] args){
         int a = 1;
         int b = 1;
         int n = 4;

         //Focus is on the below for-loop
         for(int x=1;x<=n;x++){           
             c=a+b;
         }
    }
}

现在我将如何组合这些?即我是加还是乘,为什么?提前致谢。

你的想法是对的,但那不是BigOh 要计算 BigOh,您需要 Asymptotic analysis

一位大学教授的回答很棒here,你应该看看他回答的最后一部分。

您的代码的时间复杂度为 O(n)

Is my thinking for the total number of operations in the code-snippet below valid? (Big-O notation)

不,因为 Big-O 与您正在计算的级别上的代码操作无关。引用这个 descent page about Big-O:

Big O notation is used in Computer Science to describe the performance or complexity of an algorithm. Big O specifically describes the worst-case scenario, and can be used to describe the execution time required or the space used (e.g. in memory or on disk) by an algorithm.

在你的情况下你有:

O(N) describes an algorithm whose performance will grow linearly and in direct proportion to the size of the input data set.

随着 N 的增加,您的 for 循环线性增加,因此您的代码为 O(N)。