Maybe a somewhat odd choice of language, but here is a program in ><> I have tried to optimize the execution time of. (Not golfing). The efficiency is measured in the number of required instructions on an ideal ><>-machine, which uses the same amount of time to execute each instruction.
The program does a complete factorization of a number on the stack, and prints the result. The method used is trial division of odd numbers, up to the square root of the original number. The 2-factors are calculated first. The core of this program is the third line, which wraps around, and has a minimum of 2D-program flow commands. (I have also not used p, so the source code is static, and does not modify itself.)
An online interpreter for ><> is available here.
:?!;:2%?v2n2,30.
>:3:02.
::*$}(?v::{:@%?!v2+
;n;?=1:<
,:r~:n:02. >:@
Here is a commented version:
:?!; //Checks if n is 0. Sends the next part into an infinite loop if not dealt with
:2%?v2n2,30. //Loop that gets all factors of 2
>:3:02. //Escape condition executed when the number is no longer divisible by 2, go to main loop
::*$}(?v //Main loop, the first condition checks if the candidate for trial division is > sqrt(n)
::{:@%?!v2+ //Checks divisibility by modulo, if not, increase candidate by 2
;n;?=1:< //Prints the remainder as the last factor, except when it is 1
,:r~:n:02. >:@ //When a factor is found, it is printed, n is divided, and the program goes back to the main loop
The program outputs the numbers directly, so for testing purposes, it may be convenient to separate them with commas:
:?!;:2%?v2n2,4b*o30.
>:3:02.
::*$}(?v::{:@%?!v2+
;n;?=1:<
,:r~:n4b*o:02. >:@
The main loop in detail:
The stack starts off with n,n,i ,where n is the number we are trying to factorize, and i is the iterator.
::* //The iterator is copied two times, and mad into a square. n,n,i,s
$} //The iterator is sent back to the bottom of the stack. i,n,n,s
(?v //The square is compared with n. (both values are popped). If the square is larger or equal, the instructor goes down one line. i,n
::{: //n is copied two times, the iterator called to the top, and is copied too. n,n,n,i,i
@ //The three topmost values of the stack are rotated. n,n,i,n,i
%?!v //Takes the modulo of n and the iterator, if >0, the instructor jumps over the arrow down to the next line. n,n,i
2+ //Increments the iterator by two. The line wraps back to the beginning of the loop.
I would like to know if there are optimization opportunities I have missed, and if the code is fairly readable by ><> standards. Again, this is not about golfing or obfuscating the code.
If you are testing the code with the online interpretor, there is an easy way to put a number in the initial stack (Otherwise, you get the standard ><>-error "Something smells fishy...").