Talk:Even or odd: Difference between revisions
Content added Content deleted
(Silly recursive solution) |
(→Silly recursive solution: Trickier to optimize than you seem to think…) |
||
Line 1: | Line 1: | ||
== Silly recursive solution == |
== Silly recursive solution == |
||
I made this for Java, but maybe it's not ''that'' bad in languages with recursion optimizations: |
I made this for Java, but maybe it's not ''that'' bad in languages with recursion optimizations: |
||
<lang java>public static boolean isEven(int i){ |
<lang java>public static boolean isEven(int i){ |
||
Line 7: | Line 6: | ||
return !isEven(i - 1); |
return !isEven(i - 1); |
||
}</lang> --[[User:Mwn3d|Mwn3d]] 18:47, 1 December 2011 (UTC) |
}</lang> --[[User:Mwn3d|Mwn3d]] 18:47, 1 December 2011 (UTC) |
||
: I'd be quite surprised if anything optimized that very much, as it depends on applying an operation to the result of each recursive call which is usually a sign that the compiler ''won't'' be able to figure things out. A human could split that into a pair of functions that are the logical inverse of each other (i.e., isEven and notIsEven) which could then admit optimization, but I suspect that sort of analysis isn't done by compilers (on the grounds that it would so rarely lead to real optimizations in practice). –[[User:Dkf|Donal Fellows]] 09:48, 2 December 2011 (UTC) |
Revision as of 09:48, 2 December 2011
Silly recursive solution
I made this for Java, but maybe it's not that bad in languages with recursion optimizations: <lang java>public static boolean isEven(int i){ if(i == 0) return true; if(i < 0) i = -i; return !isEven(i - 1); }</lang> --Mwn3d 18:47, 1 December 2011 (UTC)
- I'd be quite surprised if anything optimized that very much, as it depends on applying an operation to the result of each recursive call which is usually a sign that the compiler won't be able to figure things out. A human could split that into a pair of functions that are the logical inverse of each other (i.e., isEven and notIsEven) which could then admit optimization, but I suspect that sort of analysis isn't done by compilers (on the grounds that it would so rarely lead to real optimizations in practice). –Donal Fellows 09:48, 2 December 2011 (UTC)