Factorial in Befunge

Example for versions befungee 0.2.0

This example uses iterative factorial definition.The program consists of two loops — the first one calculates numbers from 16 to 1, the second one does the actual factorial calculation.

First of all we put 16 on top of the stack (as 4*4) — this will be the maximal number which has to be processed. The first loop follows, executed in clockwise order. One iteration puts into the stack a number which equals the previous one decremented. When this number becomes zero, loop breaks (_ in the second line), and the instruction pointer goes right.

Next the top element of the stack (0) is removed and 1 is placed there instead (this is the current factorial value). The second loop follows, executed in counter-clockwise order. One iteration performs the following actions:

  • \ — two top elements of the stack (the factorial calculated earlier and the next number) are swapped (the next number becomes the topmost). If the stack contains only one element, 0 is pushed on top of it.
  • :_ — if the next number is 0 (or if the stack is empty), the loop breaks.
  • . — next number is printed (its copy stays in the stack).
  • block ,,,,"! = " pushes characters in the stack and prints them immediately. The string is scanned right-to-left, but the characters are printed from topmost to lower ones, so for the programmer the string looks exactly the way it will be printed.
  • .:* — new factorial is calculated and printed (its copy stays in the stack).
  • ,*25 — newline printed.
44* >:1-:v    v ,*25 .:* ,,,,"! = ".:_ @ 
    ^    _ $1 > \:                   ^