英文:
How many primitive operations are in this statement?
问题
S = (S / (N * N)) * 100.0
原始操作:算法在伪代码中执行的基本计算。
对于上述代码,我得到了6次操作的计数。我在下面详细说明了这一点。
- 对“S”的写操作1次
- 对“S”的读操作1次
- 对“/”的操作1次
- 对第一个“N”的读操作1次
- 对第一个“*”的操作1次
- 对第二个“N”的操作0次,因为计算机已经读取了第一个“N”(不确定是否正确)。
- 对最后一个“*”的操作1次
我不确定我的计数是否正确。如果有人能够核对一下,我会很感谢。谢谢。
英文:
S = (S / (N * N)) * 100.0
Primitive operation: Basic computations performed by an algorithm in pseudocode.
For the code above I got a count of 6 operations. I have detailed this below.
- 1 operation for the write to "S"
- 1 operation for the read of "S"
- 1 operation for the "/"
- 1 operation for the read of the first "N"
- 1 operation for the first "*"
- 0 operations for the second "N" because the computer would have already read the first "N" (not sure if this is correct).
- 1 operation for the last "*"
I am not sure if my count is correct. I would apprechite if someone could double check this. Thank you.
答案1
得分: 1
根据你所说的“原始操作”是什么意思而定。
你说:
>“因为计算机可能已经读取了前面的第N个”
这可能是真的,也可能不是。这取决于Java编译器的操作。(字节码编译器和JIT编译器)。Java编译器被“允许”对此进行优化,也可以选择不优化。
但是重要的是:如果你正在计算原始操作,以便进行“第一原理”复杂性分析,那么无论你将这个语句视为5个、6个原始操作,甚至1个原始操作,都无关紧要。所有这些计算都会得出相同的答案:这个语句的时间复杂度是O(1)
。
英文:
It depends on what you mean by primitive operation.
You said:
> "because the computer would have already read the first "N" "
That may or may not be true. It depends on what the Java compilers do. (The bytecode compiler AND the JIT compiler). A Java compiler is permitted to either optimize this or not optimize it.
But here's the thing: if you are counting primitive operations so that you can perform a "first principle" complexity analysis, it won't matter if you count this statement as 5 or 6 primitive operations ... or even 1 primitive operation. All of them will give the same answer: this statement is O(1)
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论