+ 5

which is more efficient F1 or F2 ?, both give the same result, the code is C++ [Solved]

int F1 (unsigned int n) { if (n == 0) return n; int i, j; for (i = j = 1; i < 2 * n - 1; i += 2, j += i); return j; } int F2 (unsigned int n) { if (n == 0) return n; int i, j, k; for (i = j = 1; i < n; i++, j++) for (k = 0; k < n; k++, j++); return j; }

25th Mar 2018, 4:47 PM
Anthony Wainer
Anthony Wainer - avatar
2 Antworten
+ 4
Not so sure, because the addition operation j+=i uses more processing power than j++, and there are very optimized looping structures, specially in small processors (8 bit microcontrollers). So the answer will probably depend on your target circuit. In a powerful PC probably F1, in a small processor you need to count assembly instructions cycle time ;)
25th Mar 2018, 10:47 PM
Edward
Edward - avatar
+ 3
F1, it only has to run through one for loop, not multiple ones
25th Mar 2018, 4:49 PM
Ariela
Ariela - avatar