Arithmetic/Integer

From Rosetta Code

Jump to: navigation, search
Task
Arithmetic/Integer
You are encouraged to solve this task according to the task description, using any language you may know.

Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.

You may see other such operations in the Basic Data Operations category, or:


Get two integers from the user, and then output the sum, difference, product, integer quotient and remainder of those numbers. Don't include error handling. For quotient, indicate how it rounds (e.g. towards 0, towards negative infinity, etc.). For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.

Also include the exponentiation operator if one exists.

Contents

[edit] 6502 Assembly

Code is called as a subroutine (i.e. JSR Arithmetic). Specific OS/hardware routines for user input and printing are left unimplemented.

Arithmetic:	PHA			;push accumulator and X register onto stack
TXA
PHA
JSR GetUserInput ;routine not implemented
;two integers now in memory locations A and B
;addition
LDA A
CLC
ADC B
JSR DisplayAddition ;routine not implemented
 
;subtraction
LDA A
SEC
SBC B
JSR DisplaySubtraction ;routine not implemented
 
;multiplication - overflow not handled
LDA A
LDX B
Multiply: CLC
ADC A
DEX
BNE Multiply
JSR DisplayMultiply ;routine not implemented
 
;division - rounds up
LDA A
LDX #0
SEC
Divide: INX
SBC B
BCS Divide
TXA ;get result into accumulator
JSR DisplayDivide ;routine not implemented
 
;modulus
LDA A
SEC
Modulus: SBC B
BCS Modulus
ADC B
JSR DisplayModulus ;routine not implemented
 
PLA ;restore accumulator and X register from stack
TAX
PLA
RTS ;return from subroutine

The 6502 has no opcodes for multiplication, division, or modulus; the routines for multiplication, division, and modulus given above can be heavily optimized at the expense of some clarity.

[edit] Ada

with Ada.Text_Io;
with Ada.Integer_Text_IO;
 
procedure Integer_Arithmetic is
use Ada.Text_IO;
use Ada.Integer_Text_Io;
 
A, B : Integer;
begin
Get(A);
Get(B);
Put_Line("a+b = " & Integer'Image(A + B));
Put_Line("a-b = " & Integer'Image(A - B));
Put_Line("a*b = " & Integer'Image(A * B));
Put_Line("a/b = " & Integer'Image(A / B) & ", remainder " & Integer'Image(A mod B));
Put_Line("a**b = " & Integer'Image(A ** B));
 
end Integer_Arithmetic;

[edit] Aikido

 
 
var a = 0
var b = 0
stdin -> a // read int from stdin
stdin -> b // read int from stdin
 
println ("a+b=" + (a + b))
println ("a-b=" + (a - b))
println ("a*b=" + (a * b))
println ("a/b=" + (a / b))
println ("a%b=" + (a % b))
 
 

[edit] ALGOL 68

Translation of: C

Works with: ALGOL 68 version Revision 1 - no extensions to language used

Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny

main:(
LONG INT a=355, b=113;
printf(($"a+b = "gl$, a + b));
printf(($"a-b = "gl$, a - b));
printf(($"a*b = a×b = "gl$, a * b));
printf(($"a/b = "gl$, a / b));
printf(($"a OVER b = a%b = a÷b = "gl$, a % b));
printf(($"a MOD b = a%*b = a%×b = a÷×b = a÷*b = "gl$, a %* b));
printf(($"a UP b = a**b = a↑b = "gl$, a ** b))
)

Output:

a+b =                                 +468
a-b =                                 +242
a*b = a×b =                               +40115
a/b = +3.141592920353982300884955752e  +0
a OVER b = a%b = a÷b =                                   +3
a MOD b = a%*b = a%×b = a÷×b = a÷*b =                                  +16
a UP b = a**b = a↑b = +1.499007808785573768814747570e+288

ALGOL 68R has the curious (and consequently non-standard) /:= operator. This operator delivers two INTs as a result. eg.

INT quotient:=355, remainder;
remainder := quotient /:= 113;

Giving a quotient of 3, and a remainder of 16.

[edit] AmigaE

PROC main()
DEF a, b, t
WriteF('A = ')
ReadStr(stdin, t)
a := Val(t)
WriteF('B = ')
ReadStr(stdin, t)
b := Val(t)
WriteF('A+B=\d\nA-B=\d\n', a+b, a-b)
WriteF('A*B=\d\nA/B=\d\n', a*b, a/b)
/* * and / are 16 bit ops; Mul and Div are 32bit ops */
WriteF('A*B=\d\nA/B=\d\n', Mul(a,b), Div(a,b))
WriteF('A mod B =\d\n', Mod(a,b))
ENDPROC

[edit] AutoHotkey

The quotient rounds towards 0 if both inputs are integers or towards negative infinity if either input is floating point. The sign of the remainder is always the same as the sign of the first parameter (dividend).

Gui, Add, Edit, va, 5
Gui, Add, Edit, vb, -3
Gui, Add, Button, Default, Compute
Gui, Show
Return
 
ButtonCompute:
Gui, Submit
MsgBox,%
(Join`s"`n"
a "+" b " = " a+b
a "-" b " = " a-b
a "*" b " = " a*b
a "//" b " = " a//b " remainder " Mod(a,b)
a "**" b " = " a**b
)
; fallthrough
GuiClose:
ExitApp

[edit] AWK

/[0-9]* [0-9]*/{ print ($1 + $2)
print ($1 - $2)
print ($1 * $2)
print int($1 / $2)
print ($1 % $2)
exit}

[edit] BASIC

Works with: QuickBasic version 4.5

FUNCTION math(a!, b!)
PRINT a + b
PRINT a - b
PRINT a * b
PRINT a / b
PRINT a MOD b
END FUNCTION

Truncate towards: 0

Remainder sign matches: first operand

[edit] Befunge

&&00p"=A",,:."=B ",,,00g.55+,v
v,+55.+g00:,,,,"A+B="<
>"=B-A",,,,:00g-.55+,v
v,+55.*g00:,,,,"A*B="<
>"=B/A",,,,:00g/.55+,v
@,+55.%g00,,,,"A%B="<

[edit] Batch File

Works with: Windows NT version 4 or later (includes Windows XP and onward)

@set /P A=Enter 1st Number :
@set /P B=Enter 2nd Number :
@set D=%A% + %B% & call :printC
@set D=%A% - %B% & call :printC
@set D=%A% * %B% & call :printC
@set D=%A% / %B% & call :printC
@set D=%A% %% %B%
:printC
@set /A C=%D%
@echo %D% = %C%

[edit] C

#include <stdio.h>
#include <stdlib.h>
 
int main(int argc, char *argv[])
{
int a, b;
if (argc < 3) exit(1);
b = atoi(argv[--argc]);
if (b == 0) exit(2);
a = atoi(argv[--argc]);
printf("a+b = %d\n", a+b);
printf("a-b = %d\n", a-b);
printf("a*b = %d\n", a*b);
printf("a/b = %d\n", a/b); /* truncates towards 0 (in C99) */
printf("a%%b = %d\n", a%b); /* same sign as first operand (in C99) */
return 0;
}

[edit] C++

#include <iostream>
 
int main()
{
int a, b;
std::cin >> a >> b;
std::cout << "a+b = " << a+b << "\n";
std::cout << "a-b = " << a-b << "\n";
std::cout << "a*b = " << a*b << "\n";
std::cout << "a/b = " << a/b << ", remainder " << a%b << "\n";
return 0;
}

[edit] C#

using System;
 
class Program
{
static void Main(string[] args)
{
int a = Convert.ToInt32(args[0]);
int b = Convert.ToInt32(args[1]);
 
Console.WriteLine("{0} + {1} = {2}", a, b, a + b);
Console.WriteLine("{0} - {1} = {2}", a, b, a - b);
Console.WriteLine("{0} * {1} = {2}", a, b, a * b);
Console.WriteLine("{0} / {1} = {2}", a, b, a / b); // truncates towards 0
Console.WriteLine("{0} % {1} = {2}", a, b, a % b); // matches sign of first operand
Console.WriteLine("{0} to the power of {1} = {2}", a, b, Math.Pow(a, b));
}
}

Sample output:

5 + 3 = 8
5 - 3 = 2
5 * 3 = 15
5 / 3 = 1
5 % 3 = 2
5 to the power of 3 = 125

[edit] Chef

Number Soup.
 
Only reads single values.
 
Ingredients.
1 g Numbers
3 g Water
5 g Soup
 
Method.
Take Numbers from refrigerator.
Take Soup from refrigerator.
Put Numbers into 1st mixing bowl.
Add Soup into the 1st mixing bowl.
Pour contents of the 1st mixing bowl into 1st baking dish.
Clean 1st mixing bowl.
Put Numbers into 1st mixing bowl.
Remove Soup from 1st mixing bowl.
Pour contents of the 1st mixing bowl into 2nd baking dish.
Clean 1st mixing bowl.
Put Numbers into 1st mixing bowl.
Combine Soup into 1st mixing bowl.
Pour contents of the 1st mixing bowl into 3rd baking dish.
Clean 1st mixing bowl.
Put Numbers into 1st mixing bowl.
Divide Soup into 1st mixing bowl.
Pour contents of the 1st mixing bowl into 4th baking dish.
Clean 1st mixing bowl.
Put Water into 1st mixing bowl.
Verb the Soup.
Combine Numbers into 1st mixing bowl.
Verb the Soup until verbed.
Pour contents of the 1st mixing bowl into 5th baking dish.
Clean 1st mixing bowl.
 
Serves 5.

[edit] Common Lisp

(defun arithmetic (&optional (a (read *query-io*)) (b (read *query-io*)))
(mapc
(lambda (op)
(format t "~a => ~a~%" (list op a b) (funcall (symbol-function op) a b)))
'(+ - * mod rem floor ceiling truncate round expt))
(values))

Common Lisp's integer division functions are floor, ceiling, truncate, and round. They differ in how they round their quotient.

The function rounds its quotient towards
floor negative infinity
ceiling positive infinity
truncate zero
round the nearest integer (preferring the even integer if the mathematical quotient is equidistant from two integers)

Each function also returns a remainder as its secondary value, such that

 quotient * divisor + remainder = dividend .

(mod a b) and (rem a b) return numbers equal to the secondary values of (floor a b) and (truncate a b), respectively.

[edit] D

import std.stdio, std.string;
 
void main()
{
auto a = readln().atoi(), b = readln().atoi();
writefln("a + b = ", a+b);
writefln("a - b = ", a-b);
writefln("a * b = ", a*b);
writefln("a / b = ", a/b);
writefln("a % b = ", a%b);
}

[edit] E

def arithmetic(a :int, b :int) {
return `$\
Sum: ${a + b}
Difference: ${a - b}
Product: ${a * b}
Quotient: ${a // b}
Remainder: ${a % b}$\n`

}

[edit] Efene

 
@public
run = fn () {
 
First = io.get_line("First number: ")
Second = io.get_line("Second number: ")
 
A = list_to_integer(lists.delete($\n, First))
B = list_to_integer(lists.delete($\n, Second))
 
io.format("Sum: ~p~n", [A + B])
io.format("Difference: ~p~n", [A - B])
io.format("Product: ~p~n", [A * B])
io.format("Quotient: ~p~n", [A / B])
io.format("Remainder: ~p~n", [A % B])
}

[edit] Eiffel

Works with: SmartEiffel version 2.4

In a file called main.e:

class MAIN
creation make
feature make is
local
a, b: REAL;
do
print("a = ");
io.read_real;
a := io.last_real;
 
print("b = ");
io.read_real;
b := io.last_real;
 
print("a + b = ");
io.put_real(a + b);
print("%Na - b = ");
io.put_real(a - b);
print("%Na * b = ");
io.put_real(a * b);
print("%Na / b = ");
io.put_real(a / b);
print("%Na %% b = ");
io.put_real(((a / b) - (a / b).floor) * b);
print("%Na ^ b = ");
io.put_real(a.pow(b));
print("%N");
end
end

Note that there actually is a builtin modulo operator (\\). However, it seems impossible to use that instruction with SmartEiffel.

[edit] Factor

USING: combinators io kernel math math.functions math.order
math.parser prettyprint ;
 
"a=" "b=" [ write readln string>number ] bi@
{
[ + "sum: " write . ]
[ - "difference: " write . ]
[ * "product: " write . ]
[ / "quotient: " write . ]
[ /i "integer quotient: " write . ]
[ rem "remainder: " write . ]
[ mod "modulo: " write . ]
[ max "maximum: " write . ]
[ min "minimum: " write . ]
[ gcd "gcd: " write . drop ]
[ lcm "lcm: " write . ]
} 2cleave

output:

a=8
b=12
sum: 20
difference: -4
product: 96
quotient: 2/3
integer quotient: 0
remainder: 8
modulo: 8
maximum: 12
minimum: 8
gcd: 4
lcm: 24

This example illustrates the use of cleave and apply combinators to alleviate the usage of shuffle words in a concatenative language. bi@ applies a quotation to 2 inputs and 2cleave applies a sequence of quotations to 2 inputs.

[edit] FALSE

12 7
\$@$@$@$@$@$@$@$@$@$@\ { 6 copies }
"sum = "+."
difference = "-."
product = "*."
quotient = "/."
modulus = "/*-."
"

[edit] Forth

To keep the example simple, the word takes the two numbers from the stack. /mod returns two results; the stack effect is ( a b -- a%b a/b ).

: arithmetic ( a b -- )
cr ." a=" over . ." b=" dup .
cr ." a+b=" 2dup + .
cr ." a-b=" 2dup - .
cr ." a*b=" 2dup * .
cr ." a/b=" /mod .
cr ." a mod b = " . cr ;

Different host systems have different native signed division behavior. ANS Forth defines two primitive double-precision signed division operations, from which the implementation may choose the most natural to implement the basic divide operations ( / , /mod , mod , */ ). This is partly due to differing specifications in the two previous standards, Forth-79 and Forth-83.

FM/MOD ( d n -- mod div )   \ floored
SM/REM ( d n -- rem div ) \ symmetric
M* ( n n -- d )

In addition, there are unsigned variants.

UM/MOD ( ud u -- umod udiv )
UM* ( u u -- ud )

[edit] Fortran

In ANSI FORTRAN 77 or later:

 INTEGER A, B
PRINT *, 'Type in two integer numbers separated by white space',
+ ' and press ENTER'
READ *, A, B
PRINT *, ' A + B = ', (A + B)
PRINT *, ' A - B = ', (A - B)
PRINT *, ' A * B = ', (A * B)
PRINT *, ' A / B = ', (A / B)
PRINT *, 'MOD(A,B) = ', MOD(A,B)
PRINT *
PRINT *, 'Even though you did not ask, ',
+ 'exponentiation is an intrinsic op in Fortran, so...'
PRINT *, ' A ** B = ', (A ** B)
END

[edit] F#

As F# is a functional language, we can easily create a list of pairs of the string name of a function and the function itself to iterate over printing the operation and applying the function to obtain the result:

 
do
let a, b = int Sys.argv.[1], int Sys.argv.[2]
for str, f in ["+", ( + ); "-", ( - ); "*", ( * ); "/", ( / ); "%", ( % )] do
printf "%d %s %d = %d\n" a str b (f a b)
 

For example, the output with the arguments 4 and 3 is:

 
4 + 3 = 7
4 - 3 = 1
4 * 3 = 12
4 / 3 = 1
4 % 3 = 1
 

[edit] Go

import "fmt"
func arithmetic(a int, b int) {
fmt.Printf("a+b = %d\n", a+b)
fmt.Printf("a-b = %d\n", a-b)
fmt.Printf("a*b = %d\n", a*b)
fmt.Printf("a/b = %d\n", a/b) // truncates towards 0
fmt.Printf("a%%b = %d\n", a%b) // same sign as first operand
}

[edit] Groovy

def arithmetic = { a, b ->
println """
a + b = ${a} + ${b} = ${a + b}
a - b = ${a} - ${b} = ${a - b}
a * b = ${a} * ${b} = ${a * b}
a / b = ${a} / ${b} = ${a / b}  !!!
(int)(a / b) = (int)(${a} / ${b}) = ${(int)(a / b)}  !!!
a.intdiv(b) = ${a}.intdiv(${b}) = ${a.intdiv(b)}  !!!
a % b = ${a} % ${b} = ${a % b}
 
Exponentiation is also a base arithmetic operation in Groovy, so:
a ** b = ${a} ** ${b} = ${a ** b}
"""

}

Program:

arithmetic(5,3)

Output:

       a + b =        5 + 3 = 8
       a - b =        5 - 3 = 2
       a * b =        5 * 3 = 15
       a / b =        5 / 3 = 1.6666666667   !!!
(int)(a / b) = (int)(5 / 3) = 1              !!!
 a.intdiv(b) =  5.intdiv(3) = 1              !!!
       a % b =        5 % 3 = 2

Exponentiation is also a base arithmetic operation in Groovy, so:
      a ** b =       5 ** 3 = 125

[edit] Haskell

main = do
a <- readLn :: IO Integer
b <- readLn :: IO Integer
putStrLn $ "a + b = " ++ show (a + b)
putStrLn $ "a - b = " ++ show (a - b)
putStrLn $ "a * b = " ++ show (a * b)
putStrLn $ "a to the power of b = " ++ show (a ** b)
putStrLn $ "a to the power of b = " ++ show (a ^ b)
putStrLn $ "a to the power of b = " ++ show (a ^^ b)
putStrLn $ "a `div` b = " ++ show (a `div` b) -- truncates towards negative infinity
putStrLn $ "a `mod` b = " ++ show (a `mod` b) -- same sign as second operand
putStrLn $ "a `divMod` b = " ++ show (a `divMod` b)
putStrLn $ "a `quot` b = " ++ show (a `quot` b) -- truncates towards 0
putStrLn $ "a `rem` b = " ++ show (a `rem` b) -- same sign as first operand
putStrLn $ "a `quotRem` b = " ++ show (a `quotRem` b)

[edit] haXe

Compile on Neko with

haxe -neko basic_integer_arithmetic.n -main BasicIntegerArithmetic
class BasicIntegerArithmetic {
public static function main() {
var args = neko.Sys.args();
if (args.length < 2)
neko.Sys.exit(0);
var a = Std.int(args[0]);
var b = Std.int(args[1]);
trace("a+b = " + (a+b));
trace("a-b = " + (a-b));
trace("a*b = " + (a*b));
trace("a/b = " + (a/b));
trace("a%b = " + (a%b));
}
}

[edit] HicEst

All numeric is 8-byte-float. Conversions are by INT, NINT, FLOOR, CEILING, or Formatted IO

DLG(Edit=A, Edit=B, TItle='Enter numeric A and B')
WRITE(Name) A, B
WRITE() ' A + B = ', A + B
WRITE() ' A - B = ', A - B
WRITE() ' A * B = ', A * B
WRITE() ' A / B = ', A / B ! no truncation
WRITE() 'truncate A / B = ', INT(A / B) ! truncates towards 0
WRITE() 'round next A / B = ', NINT(A / B) ! truncates towards next integer
WRITE() 'round down A / B = ', FLOOR(A / B) ! truncates towards minus infinity
WRITE() 'round up A / B = ', CEILING(A / B) ! truncates towards plus infinity
WRITE() 'remainder of A / B = ', MOD(A, B) ! same sign as A
WRITE() 'A to the power of B = ', A ^ B
WRITE() 'A to the power of B = ', A ** B
A=5; B=-4;
A + B = 1
A - B = 9
A * B = -20
A / B = -1.25
truncate A / B = -1
round next A / B = -1
round down A / B = -2
round up A / B = -1
remainder of A / B = 1
A to the power of B = 16E-4
A to the power of B = 16E-4

[edit] Icon and Unicon

[edit] Icon

procedure main()
writes("Input 1st integer a := ")
a := integer(read())
writes("Input 2nd integer b := ")
b := integer(read())
 
write(" a + b = ",a+b)
write(" a - b = ",a-b)
write(" a * b = ",a*b)
write(" a / b = ",a/b, " rounds toward 0")
write(" a % b = ",a%b, " remainder sign matches a")
write(" a ^ b = ",a^b)
end

[edit] Unicon

This Icon solution works in Unicon.

[edit] J

calc    =: + , - , * , <.@% , |~ , ^
labels =: >;.2 'Sum: Difference: Product: Quotient: Remainder: Exponentiation: '
combine =: [ ,. ":@|:@,:@]
bia =: labels combine calc

Note that the verb calc produces all the processing specified for this problem, and that its output is of numeric type.

   17 calc 3
20 14 51 5 2 4913

Since other examples here provide textual output, bia produces like results.

   17 bia 3
Sum: 20
Difference: 14
Product: 51
Quotient: 5
Remainder: 2
Exponentiation: 4913

[edit] Java

import java.util.Scanner;
 
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
 
int sum = a + b;//integer addition is discouraged in print statements due to confusion with String concatenation
System.out.println("a + b = " + sum);
System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
System.out.println("quotient of a / b = " + (a / b)); // truncates towards 0
System.out.println("remainder of a / b = " + (a % b)); // same sign as first operand
}

[edit] JavaScript

In order to get user input, this solution Works with: JScript or Works with: SpiderMonkey, however the arithmetic operators are the same for any version of JavaScript.

Note that JavaScript division returns a float, even if the operands are integers.

var a = parseInt(get_input("Enter an integer"), 10);
var b = parseInt(get_input("Enter an integer"), 10);
 
WScript.Echo("a = " + a);
WScript.Echo("b = " + b);
WScript.Echo("sum: a + b = " + (a + b));
WScript.Echo("difference: a - b = " + (a - b));
WScript.Echo("product: a * b = " + (a * b));
WScript.Echo("quotient: a / b = " + (a / b));
WScript.Echo("remainder: a % b = " + (a % b));
 
function get_input(prompt) {
output(prompt);
try {
return WScript.StdIn.readLine();
} catch(e) {
return readline();
}
}
function output(prompt) {
try {
WScript.Echo(prompt);
} catch(e) {
print(prompt);
}
}

output:

Enter an integer
-147
Enter an integer
63
a = -147
b = 63
sum: a + b = -84
difference: a - b = -210
product: a * b = -9261
quotient: a / b = -2.3333333333333335
remainder: a % b = -21

[edit] Logo

to operate :a :b
(print [a =] :a)
(print [b =] :b)
(print [a + b =] :a + :b)
(print [a - b =] :a - :b)
(print [a * b =] :a * :b)
(print [a / b =] int :a / :b)
(print [a mod b =] modulo :a :b)
end

Each infix operator also has a prefix synonym (sum, difference, product, quotient). Sum and product can also have arity greater than two when used in parentheses (sum 1 2 3). Infix operators in general have high precedence; you may need to enclose their arguments in parentheses to obtain the correct expression.

[edit] LSE64

over : 2 pick
2dup : over over
 
arithmetic : \
" A=" ,t over , sp " B=" ,t dup , nl \
" A+B=" ,t 2dup + , nl \
" A-B=" ,t 2dup - , nl \
" A*B=" ,t 2dup * , nl \
" A/B=" ,t 2dup / , nl \
" A%B=" ,t  % , nl

[edit] Lua

local x = io.read()
local y = io.read()
 
print ("Sum: " , (x + y))
print ("Difference: ", (x - y))
print ("Product: " , (x * y))
print ("Quotient: " , (x / y)) -- Does not truncate
print ("Remainder: " , (x % y)) -- Result has sign of right operand
print ("Exponent: " , (x ^ y))

[edit] M4

Because of the particular nature of M4, the only user-input is the code itself. Anyway the following code can be used:

eval(A+B)
eval(A-B)
eval(A*B)
eval(A/B)
eval(A%B)

once saved in a file, e.g. operations.m4:

m4 -DA=4 -DB=6 operations.m4

or using a sort of driver:

define(`A', 4)dnl
define(`B', 6)dnl
include(`operations.m4')

[edit] Mathematica

Mathematica has all the function built-in to handle this task. Example:

a = Input["Give me an integer please!"];
b = Input["Give me another integer please!"];
Print["You gave me ", a, " and ", b];
Print["sum: ", a + b];
Print["difference: ", a - b];
Print["product: ", a b];
Print["integer quotient: ", IntegerPart[a/b]];
Print["remainder: ", Mod[a, b]];
Print["exponentiation: ", a^b];

gives back for input 17 and 3:

You gave me 17 and 3
sum: 20
difference: 14
product: 51
integer quotient: 5
remainder: 2
exponentiation: 4913

[edit] MAXScript

x = getKBValue prompt:"First number"
y = getKBValue prompt:"Second number:"
 
format "Sum: %\n" (x + y)
format "Difference: %\n" (x - y)
format "Product: %\n" (x * y)
format "Quotient: %\n" (x / y)
format "Remainder: %\n" (mod x y)

[edit] Metafont

string s[];
message "input number a: ";
s1 := readstring;
message "input number b: ";
s2 := readstring;
a := scantokens s1;
b := scantokens s2;
 
def outp(expr op) =
message "a " & op & " b = " & decimal(a scantokens(op) b) enddef;
 
outp("+");
outp("-");
outp("*");
outp("div");
outp("mod");
 
end

[edit] Modula-3

MODULE Arith EXPORTS Main;
 
IMPORT IO, Fmt;
 
VAR a, b: INTEGER;
 
BEGIN
a := IO.GetInt();
b := IO.GetInt();
IO.Put("a+b = " & Fmt.Int(a + b) & "\n");
IO.Put("a-b = " & Fmt.Int(a - b) & "\n");
IO.Put("a*b = " & Fmt.Int(a * b) & "\n");
IO.Put("a DIV b = " & Fmt.Int(a DIV b) & "\n");
IO.Put("a MOD b = " & Fmt.Int(a MOD b) & "\n");
END Arith.

[edit] MUMPS

Note: M[UMPS] has an operator called "modulo". When both operands are positive numbers, "modulo" has a result that looks a lot like "remainder"; however, there is an important difference.

To better understand the intricacies of "modulo" and how it is different from "remainder", see Donald Knuth's definition (Volume 1 of the "big books"), or find out the beauty of cyclic algebra as formulated by Niels Henrik Abel (August 5, 1802 – April 6, 1829).

Arith(first,second)	; Mathematical operators
Write "Plus",?12,first,"+",second,?25," = ",first+second,!
Write "Minus",?12,first,"-",second,?25," = ",first-second,!
Write "Multiply",?12,first,"*",second,?25," = ",first*second,!
Write "Divide",?12,first,"/",second,?25," = ",first/second,!
Write "Int Divide",?12,first,"\",second,?25," = ",first\second,!
Write "Power",?12,first,"**",second,?25," = ",first**second,!
Write "Modulo",?12,first,"#",second,?25," = ",first#second,!
Write "And",?12,first,"&",second,?25," = ",first&second,!
Write "Or",?12,first,"!",second,?25," = ",first!second,!
Quit
 
Do Arith(2,3)
Plus 2+3 = 5
Minus 2-3 = -1
Multiply 2*3 = 6
Divide 2/3 = .6666666666666666667
Int Divide 2\3 = 0
Power 2**3 = 8
Modulo 2#3 = 2
And 2&3 = 1
Or 2!3 = 1
 
Do Arith(16,0.5)
Plus 16+.5 = 16.5
Minus 16-.5 = 15.5
Multiply 16*.5 = 8
Divide 16/.5 = 32
Int Divide 16\.5 = 32
Power 16**.5 = 4
Modulo 16#.5 = 0
And 16&.5 = 1
Or 16!.5 = 1
 
Do Arith(0,2)
Plus 0+2 = 2
Minus 0-2 = -2
Multiply 0*2 = 0
Divide 0/2 = 0
Int Divide 0\2 = 0
Power 0**2 = 0
Modulo 0#2 = 0
And 0&2 = 0
Or 0!2 = 1


[edit] NSIS

All Arithmetic in NSIS is handled by the IntOp instruction. It is beyond the scope of this task to implement user input (a fairly involved task), so I will be providing hard-coded values simulating the user input, with the intention of later adding the user-input piece.

 
Function Arithmetic
Push $0
Push $1
Push $2
StrCpy $0 21
StrCpy $1 -2
 
IntOp $2 $0 + $1
DetailPrint "$0 + $1 = $2"
IntOp $2 $0 - $1
DetailPrint "$0 - $1 = $2"
IntOp $2 $0 * $1
DetailPrint "$0 * $1 = $2"
IntOp $2 $0 / $1
DetailPrint "$0 / $1 = $2"
DetailPrint "Rounding is toward negative infinity"
IntOp $2 $0 % $1
DetailPrint "$0 % $1 = $2"
DetailPrint "Sign of remainder matches the first number"
 
Pop $2
Pop $1
Pop $0
FunctionEnd
 

[edit] Objeck

 
bundle Default {
class Arithmetic {
function : Main(args : System.String[]) ~ Nil {
DoArithmetic();
}
 
function : native : DoArithmetic() ~ Nil {
a := IO.Console->GetInstance()->ReadString()->ToInt();
b := IO.Console->GetInstance()->ReadString()->ToInt();
 
IO.Console->GetInstance()->Print("a+b = ")->PrintLine(a+b);
IO.Console->GetInstance()->Print("a-b = ")->PrintLine(a-b);
IO.Console->GetInstance()->Print("a*b = ")->PrintLine(a*b);
IO.Console->GetInstance()->Print("a/b = ")->PrintLine(a/b);
}
}
}
 

[edit] OCaml

let _ =
let a = read_int ()
and b = read_int () in
 
Printf.printf "a + b = %d\n" (a + b);
Printf.printf "a - b = %d\n" (a - b);
Printf.printf "a * b = %d\n" (a * b);
Printf.printf "a / b = %d\n" (a / b); (* truncates towards 0 *)
Printf.printf "a mod b = %d\n" (a mod b) (* same sign as first operand *)
 Printf.printf "a ** b = %d\n" (a ** b);

[edit] Octave

disp("integer a: "); a = scanf("%d", 1);
disp("integer b: "); b = scanf("%d", 1);
a+b
a-b
a*b
floor(a/b)
mod(a,b)

[edit] Oz

declare
StdIn = {New class $ from Open.file Open.text end init(name:stdin)}
 
fun {ReadInt}
{String.toInt {StdIn getS($)}}
end
 
A = {ReadInt}
B = {ReadInt}
in
{ForAll
["A+B = "#A+B
"A-B = "#A-B
"A*B = "#A*B
"A/B = "#A div B %% truncates towards 0
"remainder "#A mod B %% has the same sign as A
"A^B = "#{Pow A B}
]
System.showInfo}

[edit] Pascal

program arithmetic(input, output)
 
var
a, b: integer;
 
begin
readln(a, b);
writeln('a+b = ', a+b);
writeln('a-b = ', a-b);
writeln('a*b = ', a*b);
writeln('a/b = ', a div b, ', remainder ', a mod b);
end.

[edit] Perl

Works with: Perl version 5.x

my $a = <>;
my $b = <>;
 
print
"sum: ", $a + $b, "\n",
"difference: ", $a - $b, "\n",
"product: ", $a * $b, "\n",
"integer quotient: ", int($a / $b), "\n",
"remainder: ", $a % $b, "\n",
"exponent: ", $a ** $b, "\n"
;

[edit] Perl 6

Works with: Rakudo version #21 "Seattle"

my Int $a = floor $*IN.get;
my Int $b = floor $*IN.get;
 
say 'sum: ', $a + $b;
say 'difference: ', $a - $b;
say 'product: ', $a * $b;
say 'integer quotient: ', $a div $b;
say 'remainder: ', $a % $b;
say 'exponentiation: ', $a**$b;

Note that div doesn't always do integer division; it performs the operation "most appropriate to the operand types". Synopsis 3 guarantees that div "on built-in integer types is equivalent to taking the floor of a real division". If you want integer division with other types, say floor($a/$b).

[edit] PHP

<?php
$a = fgets(STDIN);
$b = fgets(STDIN);
 
echo
"sum: ", $a + $b, "\n",
"difference: ", $a - $b, "\n",
"product: ", $a * $b, "\n",
"truncating quotient: ", (int)($a / $b), "\n",
"flooring quotient: ", floor($a / $b), "\n",
"remainder: ", $a % $b, "\n";
?>

[edit] PicoLisp

(de math (A B)
(prinl "Add " (+ A B))
(prinl "Subtract " (- A B))
(prinl "Multiply " (* A B))
(prinl "Divide " (/ A B)) # Trucates towards zero
(prinl "Div/rnd " (*/ A B)) # Rounds to next integer
(prinl "Modulus " (% A B)) # Sign of the first operand
(prinl "Power " (** A B)) )

[edit] PL/I

 
get list (a, b);
put skip list (a+b);
put skip list (a-b);
put skip list (a*b);
put skip list (trunc(a/b));
put skip list (mod(a, b));
put skip list (rem(a, b));
 

[edit] Pop11

;;; Setup token reader
vars itemrep;
incharitem(charin) -> itemrep;
;;; read the numbers
lvars a = itemrep(), b = itemrep();
;;; Print results
printf(a + b, 'a + b = %p\n');
printf(a - b, 'a - b = %p\n');
printf(a * b, 'a * b = %p\n');
printf(a div b, 'a div b = %p\n');
printf(a mod b, 'a mod b = %p\n');

[edit] PostScript

 
/arithInteger{
/x exch def
/y exch def
x y add =
x y sub =
x y mul =
x y idiv =
x y mod =
x y exp =
}def
 

[edit] PowerShell

$a = [int] (Read-Host First Number)
$b = [int] (Read-Host Second Number)
 
Write-Host "Sum: $($a + $b)"
Write-Host "Difference: $($a - $b)"
Write-Host "Product: $($a * $b)"
Write-Host "Quotient: $($a / $b)"
Write-Host "Quotient, explicitly rounded: $([Math]::Round($a / $b))"
Write-Host "Remainder: $($a % $b)"

Numbers are automatically converted to accomodate for the result. This means not only that Int32 will be expanded to Int64 but also that a non-integer quotient will cause the result to be of a floating-point type.

The remainder has the sign of the first operand.

No exponentiation operator exists, but can be worked around with the .NET BCL:

[Math]::pow($a, $b)

[edit] PureBasic

OpenConsole()
 
Define a, b
 
Print("Number 1: "): a = Val(Input())
Print("Number 2: "): b = Val(Input())
 
PrintN("Sum: " + Str(a + b))
PrintN("Difference: " + Str(a - b))
PrintN("Product: " + Str(a * b))
PrintN("Quotient: " + Str(a / b)) ; Integer division (rounding mode=truncate)
PrintN("Remainder: " + Str(a % b))
PrintN("Power: " + Str(Pow(a, b)))
 
Input()
 
CloseConsole()

[edit] Python

x = int(raw_input("Number 1: "))
y = int(raw_input("Number 2: "))
 
print "Sum: %d" % (x + y)
print "Difference: %d" % (x - y)
print "Product: %d" % (x * y)
print "Quotient: %d" % (x / y) # or x // y for newer python versions.
# truncates towards negative infinity
print "Remainder: %d" % (x % y) # same sign as second operand
print "Quotient: %d with Remainder: %d" % divmod(x, y)
 
## Only used to keep the display up when the program ends
raw_input( )

Notes: In Python3 raw_input() will be renamed to input() (the old input() built-in will go away, though one could use eval(input()) to emulate the old ... and ill-advised ... behavior). Also a better program would wrap the attempted int() conversions in a try: ... except ValueError:... construct such as:

def getnum(prompt):
while True: # retrying ...
try:
n = int(raw_input(prompt))
except ValueError:
print "Input could not be parsed as an integer. Please try again."\
continue
break
return n
 
x = getnum("Number1: ")
y = getnum("Number2: ")
...

(In general it's good practice to perform parsing of all input in exception handling blocks. This is especially true of interactive user input, but also applies to data read from configuration and other files, and marshaled from other processes via any IPC mechanism).

Python also has the procedure divmod that returns both quotient and remainder. eg

quotient, remainder = divmod(355,113)

Giving a quotient of 3, and a remainder of 16.

[edit] Python 3.0 compatible code

def arithmetic(x, y):
for op in "+ - * // %".split():
expr = "%(x)s %(op)s %(y)s" % vars()
print("%s\t=> %s" % (expr, eval(expr)))
 
 
arithmetic(12, 8)
arithmetic(input("Number 1: "), input("Number 2: "))

Output:

12 + 8  => 20
12 - 8  => 4
12 * 8  => 96
12 // 8 => 1
12 % 8  => 4
Number 1: 20
Number 2: 4
20 + 4  => 24
20 - 4  => 16
20 * 4  => 80
20 // 4 => 5
20 % 4  => 0

[edit] R

cat("insert number ")
a <- scan(nmax=1, quiet=TRUE)
cat("insert number ")
b <- scan(nmax=1, quiet=TRUE)
print(a+b)
print(a-b)
print(a*b)
print(floor(a/b))
print(a%%b)

[edit] Raven

'  Number 1: ' print expect 0 prefer as x
' Number 2: ' print expect 0 prefer as y
 
x y + " sum: %d\n" print
x y - "difference: %d\n" print
x y * " product: %d\n" print
x y / " quotient: %d\n" print
x y % " remainder: %d\n" print

[edit] REXX

say "enter 2 integer values separated by blanks"
parse pull a b
say a "+" b "=" a+b
say a "-" b "=" a-b
say a "*" b "=" a*b
say a "/" b "=" a%b "remaining" a//b "(sign from first operand)"
say a "^" b "=" a**b

sample output:

enter 2 integer values separated by blanks
17 -4
17 + -4 = 13
17 - -4 = 21
17 * -4 = -68
17 / -4 = -4 remaining 1 (sign from first operand)
17 ^ -4 = 0.0000119730367

[edit] Ruby

puts 'Enter x and y'
x=gets.to_i
y=gets.to_i
 
puts "Sum: #{x+y}",
"Difference: #{x-y}",
"Product: #{x*y}",
"Quotient: #{x/y}", # truncates towards negative infinity
"Remainder: #{x%y}" # same sign as second operand

[edit] Scala

val a = Console.readInt
val b = Console.readInt
 
val sum = a + b;//integer addition is discouraged in print statements due to confusion with String concatenation
println("a + b = " + sum);
println("a - b = " + (a - b));
println("a * b = " + (a * b));
println("quotient of a / b = " + (a / b)); // truncates towards 0
println("remainder of a / b = " + (a % b)); // same sign as first operand
 

[edit] Scheme

(define (arithmetic x y)
(for-each (lambda (op)
(write (list op x y))
(display " => ")
(write ((eval op) x y))
(write-char #\newline))
'(+ - * / quotient remainder modulo max min gcd lcm)))
 
(arithmetic 8 12)

quotient - truncates towards 0 remainder - same sign as first operand modulo - same sign as second operand

 prints this:

(+ 8 12) => 20
(- 8 12) => -4
(* 8 12) => 96
(/ 8 12) => 2/3
(quotient 8 12) => 0
(remainder 8 12) => 8
(modulo 8 12) => 8
(max 8 12) => 12
(min 8 12) => 8
(gcd 8 12) => 4
(lcm 8 12) => 24

[edit] Slate

[| :a :b |
inform: (a + b) printString.
inform: (a - b) printString.
inform: (a * b) printString.
inform: (a / b) printString.
inform: (a // b) printString.
inform: (a \\ b) printString.
 
] applyTo: {Integer readFrom: (query: 'Enter a: '). Integer readFrom: (query: 'Enter b: ')}.

[edit] Smalltalk

Works with: GNU Smalltalk

| a b |
'Input number a: ' display.
a := (stdin nextLine) asInteger.
'Input number b: ' display.
b := (stdin nextLine) asInteger.
('a+b=%1' % { a + b }) displayNl.
('a-b=%1' % { a - b }) displayNl.
('a*b=%1' % { a * b }) displayNl.
('a/b=%1' % { a // b }) displayNl.
('a%%b=%1' % { a \\ b }) displayNl.

[edit] SNOBOL4

 
output = "Enter first integer:"
first = input
output = "Enter second integer:"
second = input
output = "sum = " first + second
output = "diff = " first - second
output = "prod = " first * second
output = "quot = " (qout = first / second)
output = "rem = " first - (qout * second)
end

[edit] Standard ML

val () = let
val a = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn)))
val b = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn)))
in
print ("a + b = " ^ Int.toString (a + b) ^ "\n");
print ("a - b = " ^ Int.toString (a - b) ^ "\n");
print ("a * b = " ^ Int.toString (a * b) ^ "\n");
print ("a div b = " ^ Int.toString (a div b) ^ "\n"); (* truncates towards negative infinity *)
print ("a mod b = " ^ Int.toString (a mod b) ^ "\n"); (* same sign as second operand *)
print ("a quot b = " ^ Int.toString (Int.quot (a, b)) ^ "\n");(* truncates towards 0 *)
print ("a rem b = " ^ Int.toString (Int.rem (a, b)) ^ "\n"); (* same sign as first operand *)
print ("~a = " ^ Int.toString (~a) ^ "\n") (* unary negation, unusual notation compared to other languages *)
end

[edit] SNUSP

As a BF derivative, SNUSP only has increment and decrement as native operations. Here are routines for other basic arithmetic upon single digit numbers and results.

See also: Ethiopian Multiplication

$\
,
@
\=@@@-@-----# atoi
>
,
@
\=@@@-@-----#
<
@ # 4 copies
\=!/?!/->>+>>+>>+>>+<<<<<<<<?\#
> | #\?<<<<<<<<+>>+>>+>>+>>-/
@ |
\==/
\>>>>\
/>>>>/
@
\==!/===?\# add
< \>+<-/
@
\=@@@+@+++++# itoa
.
<
@
\==!/===?\# subtract
< \>-<-/
@
\=@@@+@+++++#
.
 !
/\
 ?- multiply
\/ #/?<<+>+>-==\ /==-<+<+>>?\# /==-<<+>>?\#
< \->+>+<<!/?/# #\?\!>>+<+<-/ #\?\!>>+<<-/
@ /==|=========|=====\ /-\ |
\======<?!/>@/<-?!\>>>@/<<<-?\=>!\?/>!/@/<#
< \=======|==========/ /-\ |
@ \done======>>>!\?/<=/
\=@@@+@+++++#
.
 !
/\
 ?- zero
\/
< divmod
@ /-\
\?\<!\?/#!===+<<<\ /-\
| \<==@\>@\>>!/?!/=<?\>!\?/<<#
| | | #\->->+</
| \=!\=?!/->>+<<?\#
@ #\?<<+>>-/
\=@@@+@+++++#
.
<
@
\=@@@+@+++++#
.
#

[edit] Tcl

puts "Please enter two numbers:"
 
set x [expr {int([gets stdin])}]; # Force integer interpretation
set y [expr {int([gets stdin])}]; # Force integer interpretation
 
puts "$x + $y = [expr {$x + $y}]"
puts "$x - $y = [expr {$x - $y}]"
puts "$x * $y = [expr {$x * $y}]"
puts "$x / $y = [expr {$x / $y}]"
puts "$x mod $y = [expr {$x % $y}]"
puts "$x 'to the' $y = [expr {$x ** $y}]"

Since Tcl doesn't really know about the "type" of a variable, the "expr" command is used to declare whatever follows as an "expression". This means there is no such thing as "integer arithmetic" and hence the kludge with int([gets stdin]).

Often, these operations would be performed in a different way from what is shown here. For example, to increase the variable "x" by the value of the variable "y", one would write

incr x $y

Also, it's important to surround the arguments to the expr in braces, especially when any of the parts of the expression are not literal constants. Discussion of this is on The Tcler's Wiki.

[edit] TI-89 BASIC

Local a, b
Prompt a, b
Disp "Sum: " & string(a + b)
Disp "Difference: " & string(a - b)
Disp "Product: " & string(a * b)
Disp "Integer quotient: " & string(intDiv(a, b))
Disp "Remainder: " & string(remain(a, b))

[edit] Toka

[ ( a b -- )
2dup ." a+b = " + . cr
2dup ." a-b = " - . cr
2dup ." a*b = " * . cr
2dup ." a/b = " / . ." remainder " mod . cr
] is mathops

[edit] UNIX Shell

With external utilities:

Works with: Bourne shell

#!/bin/sh
read a; read b;
echo "a+b = " `expr $a + $b`
echo "a-b = " `expr $a - $b`
echo "a*b = " `expr $a \* $b`
echo "a/b = " `expr $a / $b` # truncates towards 0
echo "a mod b = " `expr $a % $b` # same sign as first operand

(Notes: Using the ` (backtick operators, also available in most Bourne shells via the $(...) syntax) allows us to keep the results on their labels in the most efficient and portable way. The spaces around the operators in the expr command line arguments are required and the shell requires us to quote or escape the * character has shown, to prevent any possible "globbing" --- filename expansion of the * as a wildcard character.

With SUSv3 parameter expansions:

Works with: Almquist SHell Works with: Bourne Again SHell version 3.2 Works with: Korn SHell version 5.2.14 Works with: Z SHell

#!/bin/sh
read a; read b;
echo "a+b = $(($a+$b))"
echo "a-b = $(($a-$b))"
echo "a*b = $(($a*$b))"
echo "a/b = $(($a/$b))" # truncates towards 0
echo "a mod b = $(($a%$b))" # same sign as first operand

(Note: spaces inside the $((...)) are optional and not required; the $((...)) expressions can be inside the double quotes, but the `...` expressions could also have been enclosed in the double quotes in the previous example).

[edit] Vedit macro language

#1 = Get_Num("Give number a: ")
#2 = Get_Num("Give number b: ")
Message("a + b = ") Num_Type(#1 + #2)
Message("a - b = ") Num_Type(#1 - #2)
Message("a * b = ") Num_Type(#1 * #2)
Message("a / b = ") Num_Type(#1 / #2)
Message("a % b = ") Num_Type(#1 % #2)

[edit] VBScript

VBScript's variables are all Variants. What starts out as an integer may be converted to something else if the need arises.

[edit] Implementation
 
option explicit
dim a, b
wscript.stdout.write "A? "
a = wscript.stdin.readline
wscript.stdout.write "B? "
b = wscript.stdin.readline
 
a = int( a )
b = int( b )
 
wscript.echo "a + b=", a + b
wscript.echo "a - b=", a - b
wscript.echo "a * b=", a * b
wscript.echo "a / b=", a / b
wscript.echo "a \ b=", a \ b
wscript.echo "a mod b=", a mod b
wscript.echo "a ^ b=", a ^ b
 
[edit] Another Implementation

Gives the same output for the same input. Inspired by Python version.

 
option explicit
dim a, b
wscript.stdout.write "A? "
a = wscript.stdin.readline
wscript.stdout.write "B? "
b = wscript.stdin.readline
 
a = int( a )
b = int( b )
 
dim op
for each op in split("+ - * / \ mod ^", " ")
wscript.echo "a",op,"b=",eval( "a " & op & " b")
next
 
[edit] Invocation
C:\foo>arithmetic.vbs
A? 45
B? 11
a + b= 4511
a - b= 34
a * b= 495
a / b= 4.09090909090909
a \ b= 4
a mod b= 1
a ^ b= 1.5322783012207E+18

[edit] Visual Basic .NET

Imports System.Console
Module Module1
Sub Main
Dim a = CInt(ReadLine)
Dim b = CInt(ReadLine)
WriteLine("Sum " & a + b)
WriteLine("Difference " & a - b)
WriteLine("Product " & a - b)
WriteLine("Quotient " & a / b)
WriteLine("Integer Quotient " & a \ b)
WriteLine("Remainder " & a Mod b)
WriteLine("Exponent " & a ^ b)
End Sub
End Module

[edit] XSLT

<xsl:template name="arithmetic">
<xsl:param name="a">5</xsl:param>
<xsl:param name="b">2</xsl:param>
<fo:block>a + b = <xsl:value-of select="$a + $b"/></fo:block>
<fo:block>a - b = <xsl:value-of select="$a - $b"/></fo:block>
<fo:block>a * b = <xsl:value-of select="$a * $b"/></fo:block>
<fo:block>a / b = <xsl:value-of select="round($a div $b)"/></fo:block>
<fo:block>a mod b = <xsl:value-of select="$a mod $b"/></fo:block>
</xsl:template>
Personal tools
Support