Basic Calculator
Befunge - 37 x 5 = 185 38 x 3 = 114 characters
This is limited to integer numbers as Befunge has no floating point support.
&v /& _ #`&# "-"$# -#< v
>~:0`!#v_:" "`! #v_:","`#^_"*"`#v_&*>
^ ># $ .# @#< >&+
Explanation
The biggest distinguishing feature of Befunge is that instead of being a linear set of instructions like most languages; it is a 2d grid of single character instructions, where control can flow in any direction.
The first &
simply inputs the first number. The v
and >
then redirect control to the main path on the second row.
~:0`!#v_
This inputs a character (~
), duplicates it (:
), pushes zero onto the stack (0
), pops the top two elements and determines if the second is greater than the first (`
I'm surprised you can't use ``` to get code backticks.), inverts the truthiness of the top element (!
), then goes right if it is zero, down otherwise (#v_
).
Basically it's checking whether the input is -1
representing no more input.
># $ .# @
If the input was -1
then the duplicated input value is discarded ($
), the top of the stack is output as an integer (.
) and the program is halted (@
).
:" "`! #v_
Otherwise a similar process is repeated to determine if the input is less than or equal to a space. If it is a space then control goes down, otherwise control heads right.
^ ># $ .# @#<
If it is a space then it's redirected left (<
); the program halt (@
), output (.
) and right redirection (>
) are all skipped using #
; but the discard is executed to remove the space from the stack. Finally it's redirected up to begin the next execution (^
).
:","`#^_
If it wasn't a space the same process is used to split on if it is in [+, *]
or in [-, \]
going right and up respectively.
>~ "*"`#v_&*>
^ >&+
For [+, *]
it is again split to determine whether it is a +
or a *
. If +
it is directed down then the next number is input (&
) and they are added (+
), the control then wraps around and is redirected up to the main path for the next character. If *
then it inputs (&
) and multiplies (*
) then directly wraps around.
/& _ #`&# "-"$# -#<
For [-, \]
it starts on the right heading left. The #
's skip the character after them so the initial path is "-"`_
which simply determines if it is -
or /
. If it is /
then it continues left to input (&
) and divide (/
). If it is -
then it heads right, again skipping characters so that it executes &"-"$-
resulting in the number being input (&
) the -
character being pushed onto the stack then discarded ("-"$
) and then the subtraction being calculated (-
). The control is then redirected back to the main path.
Ruby - 74 69 67 65 characters
a=0
("+ "+$<.read).split.each_slice 2{|b,c|a=a.send b,c.to_f}
p a
Python 3, 105 bytes
Manages the four basic operations, but it only costs 5 characters each to add ^
or %
.
f=float
x,*l=input().split()
while l:o,y,*l=l;x,y=f(x),f(y);x=[x+y,x-y,x*y,x/y]['+-*/'.find(o)]
print(x)
Precedence of operations is left to right.