'How many primitive operations in a simple loop?
I have a bunch of code to find the primitive operations for. The thing is that there aren't really many detailed resources out on the web on the subject. In this loop:
for i:=0 to n do
print test
end
How many steps do we really have? In my first guess I would say n+1 considering n for the times looping and 1 for the print. Then I thought that maybe I am not precise enough. Isn't there an operation even to add 1 to i in every loop? In that matter we have n+n+1=2n+1. Is that correct?
Solution 1:[1]
This question may be from a decade ago however since the core theme of the question is of algorithm related that is important even over such period of time I feel it is critical knowing it. In Neutral Algorithm language let's look into the below example:
- sum ? 0
- for i ? 0 to n-1 do
- sum ? sum + 1
so, we already know primitive operations happens to exist when basic operations are computed by an algorithm.
Mainly when:
A. When arithmetic operations are performed (e.g +, -, *, etc)
B. When comparing two operands,
C. When assigning a value to variable,
D. When indexing an array with a value,
E. When calling a method,
F. When returning from a method and,
G. When following object reference.
so, when justify the above scenario with ultimate primitive operations we find that:
I. ONE basic operation when assigning to sum.
II. n+1 comparisons in the simple for loop (mind you have compared n times from 0 to n-1 and the other 1 comparison is which failed checking i < m. so total n+1 comparisons.
III. The third line sum has two primitive operations; 1 assigning to sum and another 1 performing arithmetic operations. which is since it is checked n times in the simple for loop it becomes 2*n= 2n;
IV. Last one but that is shadowed by the pseudocode is the increment which can be explicitly represented as i ? i+1 which has two primitive operation that is gone n times 2*n= 2n;
Overall the above example has a total of 1 + 1 + n + 2n + 2n = 5n+2 primitive operations
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | karel |
