Arithmetic/Integer: Difference between revisions

From Rosetta Code
Content added Content deleted
(→‎{{header|REXX}}: changed the program (for validating the input), add/changed comments and whitespace.)
imported>Arakov
 
(205 intermediate revisions by 97 users not shown)
Line 1: Line 1:
{{Task|Basic language learning}}
[[Category:Arithmetic operations]]
[[Category:Arithmetic operations]]
[[Category:Arithmetic]]
[[Category:Arithmetic]]
{{basic data operation}} [[Category:Simple]]
[[Category:Simple]]
{{Task|Basic language learning}}
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.
{{basic data operation}}
For quotient, indicate how it rounds (e.g. towards 0, towards negative infinity, etc.).
;Task:
Get two integers from the user,   and then (for those two integers), display their:
::::*   sum
::::*   difference
::::*   product
::::*   integer quotient
::::*   remainder
::::*   exponentiation   (if the operator exists)

<br>
Don't include error handling.

For quotient, indicate how it rounds &nbsp; (e.g. towards zero, 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.
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
<br><br>


Bonus: Include an example of the integer `divmod` operator. For example: as in [[#Haskell]], [[#Python]] and [[#ALGOL 68]]
Also include the exponentiation operator if one exists.


=={{header|0815}}==
=={{header|0815}}==
<lang 0815>
<syntaxhighlight lang="0815">
|~>|~#:end:>
|~>|~#:end:>
<:61:x<:3d:=<:20:$==$~$=${~>%<:2c:~$<:20:~$
<:61:x<:3d:=<:20:$==$~$=${~>%<:2c:~$<:20:~$
Line 24: Line 38:
}:ml:x->{x{=>~*>{x<:1:-#:ter:^:ml:
}:ml:x->{x{=>~*>{x<:1:-#:ter:^:ml:
}:ter:<:61:x<:5e:=<:20:$==$~$$=$<:62:x<:3D:=<:20:$==$~$=${{~%
}:ter:<:61:x<:5e:=<:20:$==$~$$=$<:62:x<:3D:=<:20:$==$~$=${{~%
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 35: Line 49:
a % b = 2
a % b = 2
a ^^ b = 510
a ^^ b = 510
</pre>

=={{header|11l}}==
<syntaxhighlight lang="11l">V a = Int(input())
V b = Int(input())

print(‘a + b = ’(a + b))
print(‘a - b = ’(a - b))
print(‘a * b = ’(a * b))
print(‘a / b = ’(a I/ b))
print(‘a % b = ’(a % b))
print(‘a ^ b = ’(a ^ b))</syntaxhighlight>

=={{header|360 Assembly}}==
From the principles of operation: Operands are signed and 32 bits long.
Negative quantities are held in two's-complement form.
<br>'''Multiplication:'''<br>
The product of the multiplier (the second operand) and the multiplicand
(the first operand) replaces the multiplicand. Both multiplier and
multiplicand are 32-bit signed integers. The product is always a 64-bit
signed integer and occupies an even/odd register pair.
<br>'''Division:'''<br>
The dividend (first operand) is divided by the divisor (second operand)
and replaced by the quotient and remainder. The dividend is a 64-bit
signed integer and occupies the even/odd pair of registers.
A 32-bit signed remainder and a 32-bit signed quotient replace the dividend
in the even-numbered and odd-numbered registers, respectively.
The sign of the quotient is determined by the rules of algebra.
The remainder has the same sign as the dividend.
<syntaxhighlight lang="360asm">* Arithmetic/Integer 04/09/2015
ARITHINT CSECT
USING ARITHINT,R12
LR R12,R15
ADD L R1,A
A R1,B r1=a+b
XDECO R1,BUF
MVI BUF,C'+'
XPRNT BUF,12
SUB L R1,A
S R1,B r1=a-b
XDECO R1,BUF
MVI BUF,C'-'
XPRNT BUF,12
MUL L R1,A
M R0,B r0r1=a*b
XDECO R1,BUF so r1 has the lower part
MVI BUF,C'*'
XPRNT BUF,12
DIV L R0,A
SRDA R0,32 to shift the sign
D R0,B r1=a/b and r0 has the remainder
XDECO R1,BUF so r1 has quotient
MVI BUF,C'/'
XPRNT BUF,12
MOD L R0,A
SRDA R0,32 to shift the sign
D R0,B r1=a/b and r0 has the remainder
XDECO R0,BUF so r0 has the remainder
MVI BUF,C'R'
XPRNT BUF,12
RETURN XR R15,R15
BR R14
CNOP 0,4
A DC F'53'
B DC F'11'
BUF DC CL12' '
YREGS
END ARITHINT</syntaxhighlight>
Inputs are in the code: a=53, b=11
{{out}}
<pre>
+ 64
- 42
* 583
/ 4
R 9
</pre>
</pre>


=={{header|6502 Assembly}}==
=={{header|6502 Assembly}}==
Code is called as a subroutine (i.e. JSR Arithmetic). Specific OS/hardware routines for user input and printing are left unimplemented.
Code is called as a subroutine (i.e. JSR Arithmetic). Specific OS/hardware routines for user input and printing are left unimplemented.
<lang 6502asm>Arithmetic: PHA ;push accumulator and X register onto stack
<syntaxhighlight lang="6502asm">Arithmetic: PHA ;push accumulator and X register onto stack
TXA
TXA
PHA
PHA
Line 86: Line 176:
TAX
TAX
PLA
PLA
RTS ;return from subroutine</lang>
RTS ;return from subroutine</syntaxhighlight>
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.
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.
=={{header|68000 Assembly}}==
<syntaxhighlight lang="68000devpac">ADD.L D0,D1 ; add two numbers
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
SUB.L D1,D0 ; subtract D1 from D0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
MULU D0,D1 ; multiply two unsigned numbers. Use MULS for signed numbers
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
DIVU D1,D0 ; Divide D0 by D1. Use DIVS for signed numbers. Upper two bytes of D0 are the remainder, lower two are the integer quotient.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
MODULUS:
DIVU D1,D0
SWAP D0 ;swap the order of the 16-bit halves of D0.
RTS</syntaxhighlight>

Exponentiation doesn't exist but can be implemented in a similar fashion to multiplication on the 6502:

<syntaxhighlight lang="68000devpac">Exponent:
;raises D0 to the D1 power. No overflow protection.
MOVE.L D0,D2
SUBQ.L #1,D1
loop_exponent:
MULU D0,D2
DBRA D1,loop_exponent
;output is in D2
RTS</syntaxhighlight>

=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program arith64.s */

/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

/***********************/
/* Initialized data */
/***********************/
.data
szMessError: .asciz " Two numbers in command line please ! \n" // message
szRetourLigne: .asciz "\n"
szMessResult: .asciz "resultat : @ \n" // message result
sMessValeur: .fill 12, 1, ' '
.asciz "\n"
szMessAddition: .asciz "Addition "
szMessSoustraction: .asciz "soustraction :"
szMessMultiplication: .asciz "multiplication :"
szMessDivision: .asciz "division :"
szMessReste: .asciz "remainder :"
/***********************/
/* No Initialized data */
/***********************/
.bss
qValeur: .skip 8 // reserve 8 bytes in memory
sZoneConv: .skip 30
.text
.global main
main:
mov fp,sp // fp <- stack address
ldr x0,[fp] // recup number of parameter in command line
cmp x0,3
blt error
ldr x0,[fp,16] // adresse of 1er number
bl conversionAtoD
mov x3,x0
ldr x0,[fp,24] // adresse of 2eme number
bl conversionAtoD
mov x4,x0
// addition
add x0,x3,x4
ldr x1,qAdrsZoneConv // result in x0
bl conversion10S // call function with 2 parameter (x0,x1)
ldr x0,qAdrszMessAddition
bl affichageMess // display message
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
ldr x0,qAdrsZoneConv
// soustraction
sub x0,x3,x4
ldr x1,qAdrsZoneConv // result in x0
bl conversion10S // call function with 2 parameter (x0,x1)
ldr x0,qAdrszMessSoustraction
bl affichageMess // display message
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
ldr x0,qAdrsZoneConv
// multiplication
mul x0,x3,x4
ldr x1,qAdrsZoneConv // result in x0
bl conversion10S // call function with 2 parameter (x0,x1)
ldr x0,qAdrszMessMultiplication
bl affichageMess // display message
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
ldr x0,qAdrsZoneConv
// division
mov x0,x3
mov x1,x4
udiv x0,x3,x4 // quotient
msub x3,x0,x4,x3 // remainder x3 = x3 - (x0*x4)
ldr x1,qAdrsZoneConv // result in x0
bl conversion10S // call function with 2 parameter (x0,x1)
ldr x0,qAdrszMessDivision
bl affichageMess // display message
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
ldr x0,qAdrsZoneConv

mov x0,x3 // remainder
ldr x1,qAdrsZoneConv // result in x0
bl conversion10S // call function with 2 parameter (x0,x1)
ldr x0,qAdrszMessReste
bl affichageMess // display message
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
ldr x0,qAdrsZoneConv
mov x0,0 // return code
b 100f
error:
ldr x0,qAdrszMessError
bl affichageMess // call function with 1 parameter (x0)
mov x0,1 // return code
100: // end of program
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrsMessValeur: .quad sMessValeur
qAdrszMessResult: .quad szMessResult
qAdrszMessError: .quad szMessError
qAdrszMessAddition: .quad szMessAddition
qAdrszMessSoustraction: .quad szMessSoustraction
qAdrszMessMultiplication: .quad szMessMultiplication
qAdrszMessDivision: .quad szMessDivision
qAdrszMessReste: .quad szMessReste
qAdrsZoneConv: .quad sZoneConv
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
{{Out}}
<PRE>
pi@debian-buster-64:~/asm64/rosetta/asm3 $ arith64 101 25
Addition resultat : +126
soustraction :resultat : +76
multiplication :resultat : +2525
division :resultat : +4
remainder :resultat : +1
</PRE>


=={{header|ABAP}}==
=={{header|ABAP}}==
<lang ABAP>report zz_arithmetic no standard page heading.
<syntaxhighlight lang="abap">report zz_arithmetic no standard page heading.


" Read in the two numbers from the user.
" Read in the two numbers from the user.
Line 114: Line 368:
write: / 'Integer quotient:', lv_result. " Truncated towards zero.
write: / 'Integer quotient:', lv_result. " Truncated towards zero.
lv_result = p_first mod p_second.
lv_result = p_first mod p_second.
write: / 'Remainder:', lv_result.</lang>
write: / 'Remainder:', lv_result.</syntaxhighlight>


=={{header|ACL2}}==
=={{header|ACL2}}==
<syntaxhighlight lang="lisp">
<lang Lisp>
:set-state-ok t
:set-state-ok t


Line 137: Line 391:
(cw "Product: ~x0~%" (* a b))
(cw "Product: ~x0~%" (* a b))
(cw "Quotient: ~x0~%" (floor a b))
(cw "Quotient: ~x0~%" (floor a b))
(cw "Remainder: ~x0~%" (mod a b))))))</lang>
(cw "Remainder: ~x0~%" (mod a b))))))</syntaxhighlight>

=={{header|Action!}}==
<syntaxhighlight lang="action!">DEFINE NO_KEY="255"
DEFINE KEY_Y="43"
DEFINE KEY_N="35"

PROC Main()
BYTE CH=$02FC ;Internal hardware value for last key pressed
BYTE k
INT a,b

DO
Print("Input integer value a=")
a=InputI()
Print("Input integer value b=")
b=InputI()

PrintF("a+b=%I%E",a+b)
PrintF("a-b=%I%E",a-b)
PrintF("a*b=%I%E",a*b)
PrintF("a/b=%I%E",a/b)
PrintF("a MOD b=%I%E",a MOD b)
PutE()
PrintE("Again? (Y/N)")

CH=NO_KEY ;Flush the keyboard
DO
k=CH
UNTIL k=KEY_Y OR k=KEY_N
OD
CH=NO_KEY ;Flush the keyboard

IF k=KEY_N THEN
EXIT
FI
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Arithmetic_Integer.png Screenshot from Atari 8-bit computer]
<pre>
Input integer value a=3251
Input integer value b=15
a+b=3266
a-b=3236
a*b=-16771
a/b=216
a MOD b=11

Again? (Y/N)
</pre>



=={{header|Ada}}==
=={{header|Ada}}==
<lang ada>with Ada.Text_Io;
<syntaxhighlight lang="ada">with Ada.Text_Io;
with Ada.Integer_Text_IO;
with Ada.Integer_Text_IO;


Line 159: Line 465:
Put_Line("a**b = " & Integer'Image(A ** B));
Put_Line("a**b = " & Integer'Image(A ** B));


end Integer_Arithmetic;</lang>
end Integer_Arithmetic;</syntaxhighlight>


=={{header|Aikido}}==
=={{header|Aikido}}==
<lang aikido>var a = 0
<syntaxhighlight lang="aikido">var a = 0
var b = 0
var b = 0
stdin -> a // read int from stdin
stdin -> a // read int from stdin
Line 171: Line 477:
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))</lang>
println ("a%b=" + (a % b))</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 178: Line 484:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
<lang algol68>main:(
<syntaxhighlight lang="algol68">main:(
LONG INT a=355, b=113;
LONG INT a=355, b=113;
printf(($"a+b = "gl$, a + b));
printf(($"a PLUS b = a+b = "gl$, a + b));
printf(($"a-b = "gl$, a - b));
printf(($"a MINUS b = a-b = "gl$, a - b));
printf(($"a*b = a×b = "gl$, a * b));
printf(($"a TIMES b = a*b = a×b = "gl$, a * b));
printf(($"a/b = "gl$, a / b));
printf(($"a DIV b = a/b = "gl$, a / b));
printf(($"a OVER b = a%b = 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 MOD b = a%*b = a%×b = a÷×b = a÷*b = "gl$, a %* b));
printf(($"a UP b = a**b = a↑b = "gl$, a ** b))
printf(($"a UP b = a**b = a↑b = "gl$, a ** b))
)</lang>
)</syntaxhighlight>
{{out}}
Output:
<pre>
<pre>
a+b = +468
a PLUS b = a+b = +468
a-b = +242
a MINUS b = a-b = +242
a*b = a×b = +40115
a TIMES b = a*b = a×b = +40115
a/b = +3.141592920353982300884955752e +0
a DIV b = a/b = +3.141592920353982300884955752e +0
a OVER b = a%b = a÷b = +3
a OVER b = a%b = a÷b = +3
a MOD b = a%*b = a%×b = a÷×b = a÷*b = +16
a MOD b = a%*b = a%×b = a÷×b = a÷*b = +16
a UP b = a**b = a↑b = +1.499007808785573768814747570e+288
a UP b = a**b = a↑b = +1.499007808785573768814747570e+288
</pre>
</pre>
[[ALGOL 68R]] has the curious (and consequently non-standard) /:= operator. This operator
[[ALGOL 68R]] has a non-standard '%:=' operator. This operator
delivers two INTs as a result. eg.
is equivalent to the OVERAB operator of the revised report, except it delivers the remainder as a result.
So a '/:=' b sets a to the quotient of a%b and returns the remainder of a%b as a result (Note "%" is the division operator in Algol 68, not the modulo operator - it can also be written as OVER).
This operator must be "stropped" i.e. enclosed in single quotes. eg.
INT quotient:=355, remainder;
INT quotient:=355, remainder;
remainder := quotient /:= 113;
remainder := quotient %:= 113;
Giving a quotient of 3, and a remainder of 16.
Sets quotient to 3, remainder to 16.

=={{header|ALGOL W}}==
The Algol W integer division operator (called div) truncates towards zero.<br>
The result of the modulo operator (called rem) has the sign of the first operand when the operands have different signs.
<syntaxhighlight lang="algolw">begin
integer a, b;
write( "Enter 2 integers> " );
read( a, b );
write( "a + b: ", a + b ); % addition %
write( "a - b: ", a - b ); % subtraction %
write( "a * b: ", a * b ); % multiplication %
write( "a / b: ", a div b ); % integer division %
write( "a mod b: ", a rem b ); % modulo %
% the ** operator returns a real result even with integer operands %
% ( the right-hand operand must always be an integer, the left-hand %
% operand can be integer, real or complex ) %
write( "a ^ b: ", round( a ** b ) )
end.</syntaxhighlight>


=={{header|AmigaE}}==
=={{header|AmigaE}}==
<lang amigae>PROC main()
<syntaxhighlight lang="amigae">PROC main()
DEF a, b, t
DEF a, b, t
WriteF('A = ')
WriteF('A = ')
Line 218: Line 544:
WriteF('A*B=\d\nA/B=\d\n', Mul(a,b), Div(a,b))
WriteF('A*B=\d\nA/B=\d\n', Mul(a,b), Div(a,b))
WriteF('A mod B =\d\n', Mod(a,b))
WriteF('A mod B =\d\n', Mod(a,b))
ENDPROC</lang>
ENDPROC</syntaxhighlight>

=={{header|APL}}==
<syntaxhighlight lang="apl">∇res ← integer_arithmetic; l; r
l ← ⎕
r ← ⎕
res ← 6 2 ⍴ 'sum' (l+r) 'diff' (l-r) 'prod' (l×r) 'quot' (⌊l÷r) 'rem' (r|l) 'pow' (l*r)
∇</syntaxhighlight>

Quotient will round down in this version.

=={{header|AppleScript}}==

<syntaxhighlight lang="applescript">set i1 to (text returned of (display dialog "Enter an integer value" default answer "")) as integer
set i2 to (text returned of (display dialog "Enter another integer value" default answer "")) as integer

set sum to i1 + i2
set diff to i1 - i2
set prod to i1 * i2
set quot to i1 div i2 -- Rounds towards zero.
set remainder to i1 mod i2 -- The result's sign matches the dividend's.
set exp to i1 ^ i2 -- The result's always a real.

return {|integers|:{i1, i2}, difference:diff, product:prod, quotient:quot, remainder:remainder, exponientiation:exp}</syntaxhighlight>

{{output}}

<syntaxhighlight lang="applescript">{|integers|:{-57, 2}, difference:-59, product:-114, quotient:-28, remainder:-1, exponientiation:3249.0}</syntaxhighlight>

=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">

/* ARM assembly Raspberry PI */
/* program arith.s */
/* Constantes */
.equ STDOUT, 1
.equ WRITE, 4
.equ EXIT, 1

/***********************/
/* Initialized data */
/***********************/
.data
szMessError: .asciz " Two numbers in command line please ! \n" @ message
szRetourLigne: .asciz "\n"
szMessResult: .asciz "Resultat " @ message result
sMessValeur: .fill 12, 1, ' '
.asciz "\n"
szMessAddition: .asciz "addition :"
szMessSoustraction: .asciz "soustraction :"
szMessMultiplication: .asciz "multiplication :"
szMessDivision: .asciz "division :"
szMessReste: .asciz "reste :"
/***********************/
/* No Initialized data */
/***********************/
.bss
iValeur: .skip 4 @ reserve 4 bytes in memory

.text
.global main
main:
push {fp,lr} @ save des 2 registres
add fp,sp,#8 @ fp <- adresse début
ldr r0,[fp] @ recup number of parameter in command line
cmp r0,#3
blt error
ldr r0,[fp,#8] @ adresse of 1er number
bl conversionAtoD
mov r3,r0
ldr r0,[fp,#12] @ adresse of 2eme number
bl conversionAtoD
mov r4,r0
@ addition
add r0,r3,r4
ldr r1,iAdrsMessValeur @ result in r0
bl conversion10S @ call function with 2 parameter (r0,r1)
ldr r0,iAdrszMessResult
bl affichageMess @ display message
ldr r0,iAdrszMessAddition
bl affichageMess @ display message
ldr r0,iAdrsMessValeur
bl affichageMess @ display message
@ soustraction
sub r0,r3,r4
ldr r1,=sMessValeur
bl conversion10S @ call function with 2 parameter (r0,r1)
ldr r0,iAdrszMessResult
bl affichageMess @ display message
ldr r0,iAdrszMessSoustraction
bl affichageMess @ display message
ldr r0,iAdrsMessValeur
bl affichageMess @ display message

@ multiplication
mul r0,r3,r4
ldr r1,=sMessValeur
bl conversion10S @ call function with 2 parameter (r0,r1)
ldr r0,iAdrszMessResult
bl affichageMess @ display message
ldr r0,iAdrszMessMultiplication
bl affichageMess @ display message
ldr r0,iAdrsMessValeur
bl affichageMess @ display message
@ division
mov r0,r3
mov r1,r4
bl division
mov r0,r2 @ quotient
ldr r1,=sMessValeur
bl conversion10S @ call function with 2 parameter (r0,r1)
ldr r0,iAdrszMessResult
bl affichageMess @ display message
ldr r0,iAdrszMessDivision
bl affichageMess @ display message
ldr r0,iAdrsMessValeur
bl affichageMess @ display message

mov r0,r3 @ remainder
ldr r1,=sMessValeur
bl conversion10S @ call function with 2 parameter (r0,r1)
ldr r0,iAdrszMessResult
bl affichageMess @ display message
ldr r0,iAdrszMessReste
bl affichageMess @ display message
ldr r0,iAdrsMessValeur
bl affichageMess @ display message
mov r0, #0 @ return code
b 100f
error:
ldr r0,iAdrszMessError
bl affichageMess @ call function with 1 parameter (r0)
mov r0, #1 @ return code
100: /* end of program */
mov r7, #EXIT @ request to exit program
swi 0 @ perform the system call
iAdrsMessValeur: .int sMessValeur
iAdrszMessResult: .int szMessResult
iAdrszMessError: .int szMessError
iAdrszMessAddition: .int szMessAddition
iAdrszMessSoustraction: .int szMessSoustraction
iAdrszMessMultiplication: .int szMessMultiplication
iAdrszMessDivision: .int szMessDivision
iAdrszMessReste: .int szMessReste
/******************************************************************/
/* affichage des messages avec calcul longueur */
/******************************************************************/
/* r0 contient l adresse du message */
affichageMess:
push {fp,lr} /* save des 2 registres */
push {r0,r1,r2,r7} /* save des autres registres */
mov r2,#0 /* compteur longueur */
1: /*calcul de la longueur */
ldrb r1,[r0,r2] /* recup octet position debut + indice */
cmp r1,#0 /* si 0 c est fini */
beq 1f
add r2,r2,#1 /* sinon on ajoute 1 */
b 1b
1: /* donc ici r2 contient la longueur du message */
mov r1,r0 /* adresse du message en r1 */
mov r0,#STDOUT /* code pour écrire sur la sortie standard Linux */
mov r7, #WRITE /* code de l appel systeme 'write' */
swi #0 /* appel systeme */
pop {r0,r1,r2,r7} /* restaur des autres registres */
pop {fp,lr} /* restaur des 2 registres */
bx lr /* retour procedure */
/***************************************************/
/* conversion registre en décimal signé */
/***************************************************/
/* r0 contient le registre */
/* r1 contient l adresse de la zone de conversion */
conversion10S:
push {fp,lr} /* save des 2 registres frame et retour */
push {r0-r5} /* save autres registres */
mov r2,r1 /* debut zone stockage */
mov r5,#'+' /* par defaut le signe est + */
cmp r0,#0 /* nombre négatif ? */
movlt r5,#'-' /* oui le signe est - */
mvnlt r0,r0 /* et inversion en valeur positive */
addlt r0,#1
mov r4,#10 /* longueur de la zone */
1: /* debut de boucle de conversion */
bl divisionpar10 /* division */
add r1,#48 /* ajout de 48 au reste pour conversion ascii */
strb r1,[r2,r4] /* stockage du byte en début de zone r5 + la position r4 */
sub r4,r4,#1 /* position précedente */
cmp r0,#0
bne 1b /* boucle si quotient different de zéro */
strb r5,[r2,r4] /* stockage du signe à la position courante */
subs r4,r4,#1 /* position précedente */
blt 100f /* si r4 < 0 fin */
/* sinon il faut completer le debut de la zone avec des blancs */
mov r3,#' ' /* caractere espace */
2:
strb r3,[r2,r4] /* stockage du byte */
subs r4,r4,#1 /* position précedente */
bge 2b /* boucle si r4 plus grand ou egal a zero */
100: /* fin standard de la fonction */
pop {r0-r5} /*restaur des autres registres */
pop {fp,lr} /* restaur des 2 registres frame et retour */
bx lr

/***************************************************/
/* division par 10 signé */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and http://www.hackersdelight.org/ */
/***************************************************/
/* r0 contient le dividende */
/* r0 retourne le quotient */
/* r1 retourne le reste */
divisionpar10:
/* r0 contains the argument to be divided by 10 */
push {r2-r4} /* save autres registres */
mov r4,r0
ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */
smull r1, r2, r3, r0 /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */
mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */
mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */
add r0, r2, r1 /* r0 <- r2 + r1 */
add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */
sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */
pop {r2-r4}
bx lr /* leave function */
.align 4
.Ls_magic_number_10: .word 0x66666667
/******************************************************************/
/* Conversion d une chaine en nombre stocké dans un registre */
/******************************************************************/
/* r0 contient l adresse de la zone terminée par 0 ou 0A */
conversionAtoD:
push {fp,lr} /* save des 2 registres */
push {r1-r7} /* save des autres registres */
mov r1,#0
mov r2,#10 /* facteur */
mov r3,#0 /* compteur */
mov r4,r0 /* save de l adresse dans r4 */
mov r6,#0 /* signe positif par defaut */
mov r0,#0 /* initialisation à 0 */
1: /* boucle d élimination des blancs du debut */
ldrb r5,[r4,r3] /* chargement dans r5 de l octet situé au debut + la position */
cmp r5,#0 /* fin de chaine -> fin routine */
beq 100f
cmp r5,#0x0A /* fin de chaine -> fin routine */
beq 100f
cmp r5,#' ' /* blanc au début */
bne 1f /* non on continue */
add r3,r3,#1 /* oui on boucle en avançant d un octet */
b 1b
1:
cmp r5,#'-' /* premier caracteres est - */
moveq r6,#1 /* maj du registre r6 avec 1 */
beq 3f /* puis on avance à la position suivante */
2: /* debut de boucle de traitement des chiffres */
cmp r5,#'0' /* caractere n est pas un chiffre */
blt 3f
cmp r5,#'9' /* caractere n est pas un chiffre */
bgt 3f
/* caractère est un chiffre */
sub r5,#48
ldr r1,iMaxi /*verifier le dépassement du registre */
cmp r0,r1
bgt 99f
mul r0,r2,r0 /* multiplier par facteur */
add r0,r5 /* ajout à r0 */
3:
add r3,r3,#1 /* avance à la position suivante */
ldrb r5,[r4,r3] /* chargement de l octet */
cmp r5,#0 /* fin de chaine -> fin routine */
beq 4f
cmp r5,#10 /* fin de chaine -> fin routine */
beq 4f
b 2b /* boucler */
4:
cmp r6,#1 /* test du registre r6 pour le signe */
bne 100f
mov r1,#-1
mul r0,r1,r0 /* si negatif, on multiplie par -1 */
b 100f
99: /* erreur de dépassement */
ldr r1,=szMessErrDep
bl afficheerreur
mov r0,#0 /* en cas d erreur on retourne toujours zero */
100:
pop {r1-r7} /* restaur des autres registres */
pop {fp,lr} /* restaur des 2 registres */
bx lr /* retour procedure */
/* constante programme */
iMaxi: .int 1073741824
szMessErrDep: .asciz "Nombre trop grand : dépassement de capacite de 32 bits. :\n"
.align 4
/*=============================================*/
/* division entiere non signée */
/*============================================*/
division:
/* r0 contains N */
/* r1 contains D */
/* r2 contains Q */
/* r3 contains R */
push {r4, lr}
mov r2, #0 /* r2 ? 0 */
mov r3, #0 /* r3 ? 0 */
mov r4, #32 /* r4 ? 32 */
b 2f
1:
movs r0, r0, LSL #1 /* r0 ? r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1) */
adc r3, r3, r3 /* r3 ? r3 + r3 + C. This is equivalent to r3 ? (r3 << 1) + C */
cmp r3, r1 /* compute r3 - r1 and update cpsr */
subhs r3, r3, r1 /* if r3 >= r1 (C=1) then r3 ? r3 - r1 */
adc r2, r2, r2 /* r2 ? r2 + r2 + C. This is equivalent to r2 ? (r2 << 1) + C */
2:
subs r4, r4, #1 /* r4 ? r4 - 1 */
bpl 1b /* if r4 >= 0 (N=0) then branch to .Lloop1 */
pop {r4, lr}
bx lr


</syntaxhighlight>

=={{header|Arturo}}==

<syntaxhighlight lang="rebol">a: to :integer input "give me the first number : "
b: to :integer input "give me the second number : "

print [a "+" b "=" a+b]
print [a "-" b "=" a-b]
print [a "*" b "=" a*b]
print [a "/" b "=" a/b]
print [a "%" b "=" a%b]
print [a "^" b "=" a^b]</syntaxhighlight>

{{out}}

<pre>give me the first number : 33
give me the second number : 6
33 + 6 = 39
33 - 6 = 27
33 * 6 = 198
33 / 6 = 5
33 % 6 = 3
33 ^ 6 = 12914679699</pre>


=={{header|Asymptote}}==
<syntaxhighlight lang="asymptote">int a = -12;
int b = 7;

int suma = a + b;
int resta = a - b;
int producto = a * b;
real division = a / b;
int resto = a % b;
int expo = a ** b;

write("Siendo dos enteros a = -12 y b = 7");
write(" suma de a + b = ", suma);
write(" resta de a - b = ", resta);
write(" producto de a * b = ", producto);
write(" división de a / b = ", division);
write(" resto de a mod b = ", resto);
write("exponenciación a ^ b = ", expo);</syntaxhighlight>


=={{header|AutoHotkey}}==
=={{header|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).
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).
<lang autohotkey>Gui, Add, Edit, va, 5
<syntaxhighlight lang="autohotkey">Gui, Add, Edit, va, 5
Gui, Add, Edit, vb, -3
Gui, Add, Edit, vb, -3
Gui, Add, Button, Default, Compute
Gui, Add, Button, Default, Compute
Line 240: Line 931:
; fallthrough
; fallthrough
GuiClose:
GuiClose:
ExitApp</lang>
ExitApp</syntaxhighlight>

=={{header|Avail}}==
<syntaxhighlight lang="avail">Method "arithmetic demo_,_" is
[
a : integer,
b : integer
|
Print: “a + b”;
Print: “a - b”;
Print: “a × b”; // or a * b
Print: “a ÷ b”; // or a / b, rounds toward negative infinity
Print: “a mod b”; // sign matches second argument
Print: “a ^ b”;
];
</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
<lang awk>/^[ \t]*-?[0-9]+[ \t]+-?[0-9]+[ \t]*$/ {
<syntaxhighlight lang="awk">/^[ \t]*-?[0-9]+[ \t]+-?[0-9]+[ \t]*$/ {
print "add:", $1 + $2
print "add:", $1 + $2
print "sub:", $1 - $2
print "sub:", $1 - $2
Line 250: Line 956:
print "mod:", $1 % $2 # same sign as first operand
print "mod:", $1 % $2 # same sign as first operand
print "exp:", $1 ^ $2
print "exp:", $1 ^ $2
exit }</lang>
exit }</syntaxhighlight>


For division and modulus, Awk should act like C.
For division and modulus, Awk should act like C.
Line 257: Line 963:


=={{header|BASIC}}==
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
Same code as [[#Commodore_BASIC|Commodore BASIC]]
==={{header|BaCon}}===
<syntaxhighlight lang="freebasic">' Arthimetic/Integer
DECLARE a%, b%
INPUT "Enter integer A: ", a%
INPUT "Enter integer B: ", b%
PRINT

PRINT a%, " + ", b%, " is ", a% + b%
PRINT a%, " - ", b%, " is ", a% - b%
PRINT a%, " * ", b%, " is ", a% * b%
PRINT a%, " / ", b%, " is ", a% / b%, ", trucation toward zero"
PRINT "MOD(", a%, ", ", b%, ") is ", MOD(a%, b%), ", same sign as first operand"
PRINT "POW(", a%, ", ", b%, ") is ", INT(POW(a%, b%))</syntaxhighlight>

==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="qbasic">10 input "Enter two integers separated by a comma: ";a,b
20 print " Sum: ";a+b
30 print "Difference: ";a-b
40 print " Product: ";a*b
50 print " Quontent: ";int(a/b)
60 print " Remainder: ";a mod b
70 print " Power: ";a^b</syntaxhighlight>

==={{header|Commodore BASIC}}===
<syntaxhighlight lang="basic">10 INPUT "ENTER A NUMBER"; A%
20 INPUT "ENTER ANOTHER NUMBER"; B%
30 PRINT "ADDITION:";A%;"+";B%;"=";A%+B%
40 PRINT "SUBTRACTION:";A%;"-";B%;"=";A%-B%
50 PRINT "MULTIPLICATION:";A%;"*";B%;"=";A%*B%
60 PRINT "INTEGER DIVISION:";A%;"/";B%;"=";INT(A%/B%)
70 PRINT "REMAINDER OR MODULO:";A%;"%";B%;"=";A%-INT(A%/B%)*B%
80 PRINT "POWER:";A%;"^";B%;"=";A%^B%</syntaxhighlight>

==={{header|GW-BASIC}}===
{{works with|PC-BASIC|any}}
{{works with|BASICA}}
<syntaxhighlight lang="qbasic">10 INPUT "Enter two integers separated by a comma: ";A, B
20 PRINT " Sum:"; A + B
30 PRINT "Difference:"; A - B
40 PRINT " Product:"; A * B
50 PRINT " Quontent:"; A \ B
60 PRINT " Remainder:"; A MOD B
70 PRINT " Power:"; A ^ B</syntaxhighlight>

==={{header|Minimal BASIC}}===
<syntaxhighlight lang="qbasic">10 PRINT "ENTER A INTEGER"
20 INPUT A
30 PRINT "ENTER ANOTHER INTEGER"
40 INPUT B
50 PRINT " SUM: "; A + B
60 PRINT "DIFFERENCE: "; A - B
70 PRINT " PRODUCT: "; A * B
80 PRINT " QUONTENT: "; INT(A / B)
90 PRINT " REMAINDER: "; A - INT(A / B ) * B
100 PRINT " POWER:"; A ^ B
110 END</syntaxhighlight>

==={{header|MSX Basic}}===
{{works with|MSX BASIC|any}}
<syntaxhighlight lang="qbasic">10 INPUT "Enter two integers separated by a comma: ";A, B
20 PRINT " Sum:"; A + B
30 PRINT "Difference:"; A - B
40 PRINT " Product:"; A * B
50 PRINT " Quontent:"; A \ B
60 PRINT " Remainder:"; A MOD B
70 PRINT " Power:"; A ^ B</syntaxhighlight>

==={{header|Quite BASIC}}===
<syntaxhighlight lang="qbasic">10 INPUT "enter a integer"; A
20 INPUT "enter another integer"; B
30 PRINT " Sum: "; A + B
40 PRINT "Difference: "; A - B
50 PRINT " Product: "; A * B
60 PRINT " Quontent: "; INT(A / B)
70 PRINT " Remainder: "; A - INT(A / B ) * B</syntaxhighlight>

==={{Header|Tiny BASIC}}===
<syntaxhighlight lang="Tiny BASIC"> LET A = 5
LET B = 3
PRINT "A = ", A, ", B = ", B
PRINT ""
PRINT A," + ",B," = ", A+B
PRINT A," - ",B," = ", A-B
PRINT A," * ",B," = ", A*B
PRINT A," / ",B," = ", A/B
PRINT A," % ",B," = ", A-(A/B)*B
REM Exponent calculation
LET X = 1
LET E = 0
10 IF X >= B THEN GOTO 30
LET T = E
IF E < A THEN LET E = A*A
IF T < A THEN GOTO 20
IF E >= A THEN LET E = E*A
20 LET X = X+1
GOTO 10
30 PRINT A," ^ ",B," = ", E
END</syntaxhighlight>

==={{header|True BASIC}}===
<syntaxhighlight lang="basic">
! RosettaCode: Integer Arithmetic
! True BASIC v6.007
! Translated from BaCon example.
PROGRAM Integer_Arithmetic
INPUT PROMPT "Enter integer A: ": a
INPUT PROMPT "Enter integer B: ": b
PRINT
PRINT a;" + ";b;" is ";a+b
PRINT a;" - ";b;" is ";a-b
PRINT a;" * ";b;" is ";a*b
PRINT a;" / ";b;" is ";INT(a/b);
PRINT "MOD(";a;", ";b;") is "; MOD(a,b)
PRINT "POW(";a;", ";b;") is ";INT(a^b)
GET KEY done
END</syntaxhighlight>

==={{header|QBasic}}===
{{works with|QuickBasic|4.5}}
{{works with|QuickBasic|4.5}}
<lang qbasic>function math(a!, b!)
<syntaxhighlight lang="qbasic">function math(a!, b!)
print a + b
print a + b
print a - b
print a - b
Line 264: Line 1,091:
print a / b
print a / b
print a mod b
print a mod b
end function</lang>
end function</syntaxhighlight>
Truncate towards: 0
Truncate towards: 0


Remainder sign matches: first operand
Remainder sign matches: first operand

==={{header|XBasic}}===
{{works with|Windows XBasic}}
<syntaxhighlight lang="qbasic">PROGRAM "IntegerArithmetic"
VERSION "0.0000"

DECLARE FUNCTION Entry ()

FUNCTION Entry ()
a$ = INLINE$("Enter integer A: ")
a = SLONG(a$)
b$ = INLINE$("Enter integer B: ")
b = SLONG(b$)
PRINT
PRINT " Sum:"; a + b
PRINT "Difference:"; a - b
PRINT " Product:"; a * b
PRINT " Quontent:"; a / b
PRINT " Remainder:"; a MOD b
PRINT " Power:"; a ** b
END FUNCTION
END PROGRAM</syntaxhighlight>


=={{header|BASIC256}}==
=={{header|BASIC256}}==
<syntaxhighlight lang="basic256">
<lang BASIC256>
input "enter a number ?", a
input "enter a number ?", a
input "enter another number ?", b
input "enter another number ?", b
Line 280: Line 1,129:
print "remainder or modulo " + a + " % " + b + " = " + (a % b)
print "remainder or modulo " + a + " % " + b + " = " + (a % b)
print "power " + a + " ^ " + b + " = " + (a ^ b)
print "power " + a + " ^ " + b + " = " + (a ^ b)
</syntaxhighlight>
</lang>


=={{header|Batch File}}==
=={{header|Batch File}}==
{{works with|Windows NT|4 or later (includes Windows XP and onward)}}
{{works with|Windows 7| or later, haven't checked earlier versions}}
<lang dos>
<syntaxhighlight lang="dos">
set /p equation=
@echo off
set /P A=Enter 1st Number :
set /a result=%equation%
echo %result%
set /P B=Enter 2nd Number :
pause
set D=%A% + %B% & call :printC
</syntaxhighlight>
set D=%A% - %B% & call :printC
set D=%A% * %B% & call :printC
set D=%A% / %B% & call :printC & rem truncates toward 0
set D=%A% %% %B% & call :printC & rem matches sign of 1st operand
exit /b

:printC
set /A C=%D%
echo %D% = %C%
</lang>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<lang bbcbasic> INPUT "Enter the first integer: " first%
<syntaxhighlight lang="bbcbasic"> INPUT "Enter the first integer: " first%
INPUT "Enter the second integer: " second%
INPUT "Enter the second integer: " second%
Line 309: Line 1,149:
PRINT "The integer quotient is " ; first% DIV second% " (rounds towards 0)"
PRINT "The integer quotient is " ; first% DIV second% " (rounds towards 0)"
PRINT "The remainder is " ; first% MOD second% " (sign matches first operand)"
PRINT "The remainder is " ; first% MOD second% " (sign matches first operand)"
PRINT "The first raised to the power of the second is " ; first% ^ second%</lang>
PRINT "The first raised to the power of the second is " ; first% ^ second%</syntaxhighlight>


=={{header|bc}}==
=={{header|bc}}==
<lang bc>define f(a, b) {
<syntaxhighlight lang="bc">define f(a, b) {
"add: "; a + b
"add: "; a + b
"sub: "; a - b
"sub: "; a - b
Line 319: Line 1,159:
"mod: "; a % b /* same sign as first operand */
"mod: "; a % b /* same sign as first operand */
"pow: "; a ^ b
"pow: "; a ^ b
}</lang>
}</syntaxhighlight>


=={{header|Befunge}}==
=={{header|Befunge}}==
<lang befunge>&&00p"=A",,:."=B ",,,00g.55+,v
<syntaxhighlight lang="befunge">&&00p"=A",,:."=B ",,,00g.55+,v
v,+55.+g00:,,,,"A+B="<
v,+55.+g00:,,,,"A+B="<
>"=B-A",,,,:00g-.55+,v
>"=B-A",,,,:00g-.55+,v
v,+55.*g00:,,,,"A*B="<
v,+55.*g00:,,,,"A*B="<
>"=B/A",,,,:00g/.55+,v
>"=B/A",,,,:00g/.55+,v
@,+55.%g00,,,,"A%B="<</lang>
@,+55.%g00,,,,"A%B="<</syntaxhighlight>

=={{header|BQN}}==
<pre>•Out "Enter number 1: "
a ← •BQN •GetLine @
•Out "Enter number 2: "
b ← •BQN •GetLine @

•Show a + b
•Show a - b
•Show a × b
•Show a ÷ b
•Show b | a
•Show a ⋆ b</pre>
<pre>Enter number 1:
12
Enter number 2:
2
14
10
24
6
0
144</pre>



=={{header|Bracmat}}==
=={{header|Bracmat}}==
The remainder returned by mod is non-negative. Furthermore, <code>div$(!a.!d)*!d+mod$(!a.!d):!a</code> for all integer <code>!a</code> and <code>!d</code>, <code>!d:~0</code>.
The remainder returned by mod is non-negative. Furthermore, <code>div$(!a.!d)*!d+mod$(!a.!d):!a</code> for all integer <code>!a</code> and <code>!d</code>, <code>!d:~0</code>.
<lang Bracmat> ( enter
<syntaxhighlight lang="bracmat"> ( enter
= put$"Enter two integer numbers, separated by space:"
= put$"Enter two integer numbers, separated by space:"
& get':(~/#?k_~/#?m|quit:?k)
& get':(~/#?k_~/#?m|quit:?k)
Line 348: Line 1,212:
& out$("Exponentiation:" !k^!m)
& out$("Exponentiation:" !k^!m)
& done;
& done;
</syntaxhighlight>
</lang>


=={{header|Brat}}==
=={{header|Brat}}==
Inspired by the second VBScript version.
Inspired by the second VBScript version.
<lang brat>x = ask("First number: ").to_i
<syntaxhighlight lang="brat">x = ask("First number: ").to_i
y = ask("Second number: ").to_i
y = ask("Second number: ").to_i


Line 358: Line 1,222:
#Remainder uses sign of right hand side
#Remainder uses sign of right hand side
[:+ :- :* :/ :% :^].each { op |
[:+ :- :* :/ :% :^].each { op |
p "#{x} #{op} #{y} = #{x.call_method op, y}"</lang>
p "#{x} #{op} #{y} = #{x.call_method op, y}"</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>


Line 377: Line 1,241:
printf("a%%b = %d\n", a%b); /* same sign as first operand (in C99) */
printf("a%%b = %d\n", a%b); /* same sign as first operand (in C99) */
return 0;
return 0;
}</lang>
}</syntaxhighlight>

=={{header|C++}}==
<lang cpp>#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;
}</lang>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;


class Program
class Program
Line 410: Line 1,260:
Console.WriteLine("{0} to the power of {1} = {2}", a, b, Math.Pow(a, b));
Console.WriteLine("{0} to the power of {1} = {2}", a, b, Math.Pow(a, b));
}
}
}</lang>
}</syntaxhighlight>
{{out}}
Sample output:
<pre>5 + 3 = 8
<pre>5 + 3 = 8
5 - 3 = 2
5 - 3 = 2
Line 418: Line 1,268:
5 % 3 = 2
5 % 3 = 2
5 to the power of 3 = 125</pre>
5 to the power of 3 = 125</pre>

=={{header|C++}}==
<syntaxhighlight lang="cpp">#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;
}</syntaxhighlight>


=={{header|Chef}}==
=={{header|Chef}}==


<lang Chef>Number Soup.
<syntaxhighlight lang="chef">Number Soup.


Only reads single values.
Only reads single values.
Line 456: Line 1,320:
Clean 1st mixing bowl.
Clean 1st mixing bowl.


Serves 5.</lang>
Serves 5.</syntaxhighlight>


=={{header|Clipper}}==
=={{header|Clipper}}==
<lang visualfoxpro>procedure Test( a, b )
<syntaxhighlight lang="visualfoxpro">procedure Test( a, b )
? "a+b", a + b
? "a+b", a + b
? "a-b", a - b
? "a-b", a - b
Line 469: Line 1,333:
// Exponentiation is also a base arithmetic operation
// Exponentiation is also a base arithmetic operation
? "a**b", a ** b
? "a**b", a ** b
return</lang>
return</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(defn myfunc []
<syntaxhighlight lang="clojure">(defn myfunc []
(println "Enter x and y")
(println "Enter x and y")
(let [x (read), y (read)]
(let [x (read), y (read)]
(doseq [op '(+ - * / Math/pow rem)]
(doseq [op '(+ - * / Math/pow rem)]
(let [exp (list op x y)]
(let [exp (list op x y)]
(printf "%s=%s\n" exp (eval exp))))))</lang>
(printf "%s=%s\n" exp (eval exp))))))</syntaxhighlight>


<pre>user=> (myfunc)
<pre>user=> (myfunc)
Line 492: Line 1,356:


=={{header|COBOL}}==
=={{header|COBOL}}==
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. Int-Arithmetic.
PROGRAM-ID. Int-Arithmetic.


Line 535: Line 1,399:


GOBACK
GOBACK
.</lang>
.</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==


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


Common Lisp's integer division functions are <code>floor</code>, <code>ceiling</code>, <code>truncate</code>, and <code>round</code>. They differ in how they round their quotient.
Common Lisp's integer division functions are <code>floor</code>, <code>ceiling</code>, <code>truncate</code>, and <code>round</code>. They differ in how they round their quotient.
Line 570: Line 1,434:
=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
Works with Gardens Point Component Pascal
Works with Gardens Point Component Pascal
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE Arithmetic;
MODULE Arithmetic;
IMPORT CPmain,Console,RTS;
IMPORT CPmain,Console,RTS;
Line 599: Line 1,463:
Console.WriteString("x MOD y >");Console.WriteInt(x MOD y,6);Console.WriteLn;
Console.WriteString("x MOD y >");Console.WriteInt(x MOD y,6);Console.WriteLn;
END Arithmetic.
END Arithmetic.
</syntaxhighlight>
</lang>
command: <i>cprun Arithmetic 12 23</i><br/>
command: <i>cprun Arithmetic 12 23</i><br/>
{{out}}
output:
<pre>
<pre>
x + y > 35
x + y > 35
Line 610: Line 1,474:
</pre>
</pre>
Works with BlackBox Component Builder
Works with BlackBox Component Builder
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE Arithmetic;
MODULE Arithmetic;
IMPORT StdLog,DevCommanders,TextMappers;
IMPORT StdLog,DevCommanders,TextMappers;
Line 644: Line 1,508:
END Go;
END Go;
END Arithmetic.
END Arithmetic.
</syntaxhighlight>
</lang>
Command: Arithmetic.Go 12 23 ~ <br/>
Command: Arithmetic.Go 12 23 ~ <br/>
{{out}}
Output:
<pre>
<pre>
x + y > 35
x + y > 35
Line 654: Line 1,518:
x MOD y > 12
x MOD y > 12
</pre>
</pre>

=={{header|Crystal}}==
<syntaxhighlight lang="crystal">a = gets.not_nil!.to_i64
b = gets.not_nil!.to_i64

puts "Sum: #{a + b}"
puts "Difference: #{a - b}"
puts "Product: #{a * b}"
puts "Quotient (float division): #{a / b}" # / always returns a float.
puts "Quotient (floor division): #{a // b}"
puts "Remainder: #{a % b}" # Sign of remainder matches that of the second operand (b).
puts "Power: #{a ** b}" # Integers can only be raised to a positive exponent.
</syntaxhighlight>

=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio, std.string, std.conv;
<syntaxhighlight lang="d">import std.stdio, std.string, std.conv;


void main() {
void main() {
Line 671: Line 1,549:
writeln("a % b = ", a % b);
writeln("a % b = ", a % b);
writeln("a ^^ b = ", a ^^ b);
writeln("a ^^ b = ", a ^^ b);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>a = -16, b = 5
<pre>a = -16, b = 5
Line 680: Line 1,558:
a % b = -1
a % b = -1
a ^^ b = -1048576</pre>
a ^^ b = -1048576</pre>

===Shorter Version===
===Shorter Version===
Same output.
Same output.
<lang d>import std.stdio, std.string, std.conv, std.typetuple;
<syntaxhighlight lang="d">import std.stdio, std.string, std.conv, std.meta;


void main() {
void main() {
Line 692: Line 1,571:
writeln("a = ", a, ", b = ", b);
writeln("a = ", a, ", b = ", b);


foreach (op; TypeTuple!("+", "-", "*", "/", "%", "^^"))
foreach (op; AliasSeq!("+", "-", "*", "/", "%", "^^"))
mixin(`writeln("a ` ~ op ~ ` b = ", a` ~ op ~ `b);`);
mixin(`writeln("a ` ~ op ~ ` b = ", a` ~ op ~ `b);`);
}</lang>
}</syntaxhighlight>
Division and modulus are defined as in C99.
Division and modulus are defined as in C99.

=={{header|Dart}}==
<syntaxhighlight lang="dart">import 'dart:io';
import 'dart:math' show pow;

void main() {
print('enter a integer: ');
int a = int.parse(stdin.readLineSync());
print('enter another integer: ');
int b = int.parse(stdin.readLineSync());

print('a + b = ${a + b}');
print('a - b = ${a - b}');
print('a * b = ${a * b}');
print('a / b = ${a ~/ b}');
print('a % b = ${a % b}');
print('a ^ b = ${pow(a, b)}');

//Integer division uses the '~/' operator
}</syntaxhighlight>


=={{header|dc}}==
=={{header|dc}}==
<lang dc>[Enter 2 integers on 1 line.
<syntaxhighlight lang="dc">[Enter 2 integers on 1 line.
Use whitespace to separate. Example: 2 3
Use whitespace to separate. Example: 2 3
Use underscore for negative integers. Example: _10
Use underscore for negative integers. Example: _10
Line 707: Line 1,606:
[div: ]P la lb / p sz [truncates toward zero]sz
[div: ]P la lb / p sz [truncates toward zero]sz
[mod: ]P la lb % p sz [sign matches first operand]sz
[mod: ]P la lb % p sz [sign matches first operand]sz
[pow: ]P la lb ^ p sz</lang>
[pow: ]P la lb ^ p sz</syntaxhighlight>

=={{header|DCL}}==
=={{header|DCL}}==
<lang DCL>$ inquire a "Enter first number"
<syntaxhighlight lang="dcl">$ inquire a "Enter first number"
$ a = f$integer( a )
$ a = f$integer( a )
$ inquire b "Enter second number"
$ inquire b "Enter second number"
Line 716: Line 1,616:
$ write sys$output "a - b = ", a - b
$ write sys$output "a - b = ", a - b
$ write sys$output "a * b = ", a * b
$ write sys$output "a * b = ", a * b
$ write sys$output "a / b = ", a / b ! truncates down</lang>
$ write sys$output "a / b = ", a / b ! truncates down</syntaxhighlight>
{{out}}
{{out}}
<pre>$ @arithmetic_integer
<pre>$ @arithmetic_integer
Line 734: Line 1,634:


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang Delphi>program IntegerArithmetic;
<syntaxhighlight lang="delphi">program IntegerArithmetic;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 752: Line 1,652:
WriteLn(Format('%d %% %d = %d', [a, b, a mod b])); // matches sign of the first operand
WriteLn(Format('%d %% %d = %d', [a, b, a mod b])); // matches sign of the first operand
WriteLn(Format('%d ^ %d = %d', [a, b, Trunc(Power(a, b))]));
WriteLn(Format('%d ^ %d = %d', [a, b, Trunc(Power(a, b))]));
end.</lang>
end.</syntaxhighlight>


=={{header|DWScript}}==
=={{header|DWScript}}==
<lang delphi>var a := StrToInt(ParamStr(0));
<syntaxhighlight lang="delphi">var a := StrToInt(ParamStr(0));
var b := StrToInt(ParamStr(1));
var b := StrToInt(ParamStr(1));


Line 763: Line 1,663:
PrintLn(Format('%d / %d = %d', [a, b, a div b]));
PrintLn(Format('%d / %d = %d', [a, b, a div b]));
PrintLn(Format('%d mod %d = %d', [a, b, a mod b]));
PrintLn(Format('%d mod %d = %d', [a, b, a mod b]));
PrintLn(Format('%d ^ %d = %d', [a, b, Trunc(Power(a, b))]));</lang>
PrintLn(Format('%d ^ %d = %d', [a, b, Trunc(Power(a, b))]));</syntaxhighlight>

=={{header|Dyalect}}==

{{trans|Swift}}

Dyalect has no operator for exponential.

<syntaxhighlight lang="dyalect">let a = 6
let b = 4
print("sum = \(a+b)")
print("difference = \(a-b)")
print("product = \(a*b)")
print("Integer quotient = \(a/b)")
print("Remainder = \(a%b)")</syntaxhighlight>


=={{header|E}}==
=={{header|E}}==


<lang e>def arithmetic(a :int, b :int) {
<syntaxhighlight lang="e">def arithmetic(a :int, b :int) {
return `$\
return `$\
Sum: ${a + b}
Sum: ${a + b}
Line 774: Line 1,689:
Quotient: ${a // b}
Quotient: ${a // b}
Remainder: ${a % b}$\n`
Remainder: ${a % b}$\n`
}</lang>
}</syntaxhighlight>

=={{header|EasyLang}}==

<syntaxhighlight lang="text">a = number input
b = number input
print a + b
print a - b
print a * b
print a div b
print a mod b
print pow a b</syntaxhighlight>


=={{header|ECL}}==
=={{header|ECL}}==
<syntaxhighlight lang="ecl">
<lang ECL>
ArithmeticDemo(INTEGER A,INTEGER B) := FUNCTION
ArithmeticDemo(INTEGER A,INTEGER B) := FUNCTION
ADDit := A + B;
ADDit := A + B;
Line 809: Line 1,735:
This default behavior can be changed
This default behavior can be changed
*/
*/
</syntaxhighlight>
</lang>


=={{header|Efene}}==
=={{header|Efene}}==


<lang efene>@public
<syntaxhighlight lang="efene">@public
run = fn () {
run = fn () {


Line 827: Line 1,753:
io.format("Quotient: ~p~n", [A / B])
io.format("Quotient: ~p~n", [A / B])
io.format("Remainder: ~p~n", [A % B])
io.format("Remainder: ~p~n", [A % B])
}</lang>
}</syntaxhighlight>


=={{header|Eiffel}}==
=={{header|Eiffel}}==
{{works with|SmartEiffel|2.4}}
{{works with|SmartEiffel|2.4}}
In a file called main.e:
In a file called main.e:
<lang eiffel>class MAIN
<syntaxhighlight lang="eiffel">class MAIN
creation make
creation make
feature make is
feature make is
Line 860: Line 1,786:
print("%N");
print("%N");
end
end
end</lang>
end</syntaxhighlight>
Note that there actually is a builtin modulo operator (\\). However, it seems impossible to use that instruction with SmartEiffel.
Note that there actually is a builtin modulo operator (\\). However, it seems impossible to use that instruction with SmartEiffel.


=={{header|Elena}}==
=={{header|Elena}}==
ELENA 6.x :
<lang elena>#define system.
#define system'math.
<syntaxhighlight lang="elena">import system'math;
#define extensions.
import extensions;


public program()
// --- Program ---
{
var a := console.loadLineTo(new Integer());
var b := console.loadLineTo(new Integer());
console.printLine(a," + ",b," = ",a + b);
console.printLine(a," - ",b," = ",a - b);
console.printLine(a," * ",b," = ",a * b);
console.printLine(a," / ",b," = ",a / b); // truncates towards 0
console.printLine(a," % ",b," = ",a.mod(b)); // matches sign of first operand
console.printLine(a," ^ ",b," = ",a ^ b);
}</syntaxhighlight>


=={{header|Elixir}}==
#symbol program =
{{works with|Elixir|1.4}}
[
<syntaxhighlight lang="elixir">defmodule Arithmetic_Integer do
#var a := console readLine:(Integer new).
# Function to remove line breaks and convert string to int
#var b := console readLine:(Integer new).
defp get_int(msg) do
IO.gets(msg) |> String.strip |> String.to_integer
end
def task do
# Get user input
a = get_int("Enter your first integer: ")
b = get_int("Enter your second integer: ")
IO.puts "Elixir Integer Arithmetic:\n"
console writeLine:a:" + ": b:" = ":(a + b).
console writeLine:a:" - ": b:" = ":(a - b).
IO.puts "Sum: #{a + b}"
console writeLine:a:" * ": b:" = ":(a * b).
IO.puts "Difference: #{a - b}"
console writeLine:a:" / ": b:" = ":(a / b). // truncates towards 0
IO.puts "Product: #{a * b}"
console writeLine:a:" % ":b:" = ":(a mod:b). // matches sign of first operand
IO.puts "True Division: #{a / b}" # Float
IO.puts "Division: #{div(a,b)}" # Truncated Towards 0
].</lang>
IO.puts "Floor Division: #{Integer.floor_div(a,b)}" # floored integer division
IO.puts "Remainder: #{rem(a,b)}" # Sign from first digit
IO.puts "Modulo: #{Integer.mod(a,b)}" # modulo remainder (uses floored division)
IO.puts "Exponent: #{:math.pow(a,b)}" # Float, using Erlang's :math
end
end

Arithmetic_Integer.task</syntaxhighlight>

{{out}}
<pre style="height: 80ex; overflow: scroll">
C:\Elixir>elixir Arithmetic_Integer.exs
Enter your first integer: 7
Enter your second integer: 3
Elixir Integer Arithmetic:

Sum: 10
Difference: 4
Product: 21
True Division: 2.3333333333333335
Division: 2
Floor Division: 2
Remainder: 1
Modulo: 1
Exponent: 343.0

C:\Elixir>elixir Arithmetic_Integer.exs
Enter your first integer: -7
Enter your second integer: 3
Elixir Integer Arithmetic:

Sum: -4
Difference: -10
Product: -21
True Division: -2.3333333333333335
Division: -2
Floor Division: -3
Remainder: -1
Modulo: 2
Exponent: -343.0

C:\Elixir>elixir Arithmetic_Integer.exs
Enter your first integer: 7
Enter your second integer: -3
Elixir Integer Arithmetic:

Sum: 4
Difference: 10
Product: -21
True Division: -2.3333333333333335
Division: -2
Floor Division: -3
Remainder: 1
Modulo: -2
Exponent: 0.0029154518950437317

C:\Elixir>elixir Arithmetic_Integer.exs
Enter your first integer: -7
Enter your second integer: -3
Elixir Integer Arithmetic:

Sum: -10
Difference: -4
Product: 21
True Division: 2.3333333333333335
Division: 2
Floor Division: 2
Remainder: -1
Modulo: -1
Exponent: -0.0029154518950437317
</pre>

=={{header|EMal}}==
<syntaxhighlight lang="emal">
^|EMal has no divmod operator or built-in function,
|its interface can be easily emulated as shown below.
|The performace is worse than using / and % operators.
|^
fun divmod = Pair by int dividend, int divisor
Pair result = int%int().named("quotient", "remainder")
result.quotient = dividend / divisor
result.remainder = dividend % divisor
return result
end
fun main = int by List args
int a, b
if args.length == 2
a = int!args[0]
b = int!args[1]
else
a = ask(int, "first number: ")
b = ask(int, "second number: ")
end
writeLine("sum: " + (a + b))
writeLine("difference: " + (a - b))
writeLine("product: " + (a * b))
writeLine("integer quotient: " + (a / b)) # truncates towards 0
writeLine("remainder: " + (a % b)) # matches sign of first operand
writeLine("exponentiation: " + (a ** b))
writeLine("logarithm: " + (a // b))
writeLine("divmod: " + divmod(a, b))
return 0
end
exit main(Runtime.args)
</syntaxhighlight>
{{out}}
<pre>
emal.exe Org\RosettaCode\AritmeticInteger.emal
first number: 19
second number: 7
sum: 26
difference: 12
product: 133
integer quotient: 2
remainder: 5
exponentiation: 893871739
logarithm: 2
divmod: [2,5]
</pre>

=={{header|Emojicode}}==
<syntaxhighlight lang="emojicode">🏁🍇
🍺🔢🆕🔡▶️👂🏼❗ 10❗️ ➡️ x 💭 Get first number
🍺🔢🆕🔡▶️👂🏼❗ 10❗️ ➡️ y 💭 Get second number
😀 🔤Sum: 🧲x➕y🧲🔤 ❗
😀 🔤Difference: 🧲x➖y🧲🔤 ❗
😀 🔤Product: 🧲x✖️y🧲🔤 ❗
😀 🔤Quotient: 🧲x➗️y🧲🔤 ❗ 💭 Rounds towards 0
😀 🔤Remainder: 🧲x🚮️y🧲🔤 ❗ 💭 Matches sign of first operand
🍉️</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>% Implemented by Arjun Sunel
<syntaxhighlight lang="erlang">% Implemented by Arjun Sunel
-module(arith).
-module(arith).
-export([start/0]).
-export([start/0]).
Line 897: Line 1,972:
halt()
halt()
end.
end.
</syntaxhighlight>
</lang>


=={{header|ERRE}}==
=={{header|ERRE}}==
<lang>
<syntaxhighlight lang="text">
PROGRAM INTEGER_ARITHMETIC
PROGRAM INTEGER_ARITHMETIC


Line 920: Line 1,995:
PRINT("Power ";A;"^";B;"=";(A^B))
PRINT("Power ";A;"^";B;"=";(A^B))
END PROGRAM
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Enter a number ? 12
<pre>Enter a number ? 12
Line 938: Line 2,013:


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>include get.e
<syntaxhighlight lang="euphoria">include get.e


integer a,b
integer a,b
Line 950: Line 2,025:
printf(1,"a / b = %g\n", a/b) -- does not truncate
printf(1,"a / b = %g\n", a/b) -- does not truncate
printf(1,"remainder(a,b) = %d\n", remainder(a,b)) -- same sign as first operand
printf(1,"remainder(a,b) = %d\n", remainder(a,b)) -- same sign as first operand
printf(1,"power(a,b) = %g\n", power(a,b))</lang>
printf(1,"power(a,b) = %g\n", power(a,b))</syntaxhighlight>


{{out}}
Output:
<pre>a = 2
<pre>a = 2
b = 3
b = 3
Line 967: Line 2,042:


For sum, type in C1
For sum, type in C1
<lang excel>
<syntaxhighlight lang="excel">
=$A1+$B1
=$A1+$B1
</syntaxhighlight>
</lang>


For difference, type in D1
For difference, type in D1
<lang excel>
<syntaxhighlight lang="excel">
=$A1-$B1
=$A1-$B1
</syntaxhighlight>
</lang>


For product, type in E1
For product, type in E1
<lang excel>
<syntaxhighlight lang="excel">
=$A1*$B1
=$A1*$B1
</syntaxhighlight>
</lang>


For quotient, type in F1
For quotient, type in F1
<lang excel>
<syntaxhighlight lang="excel">
=QUOTIENT($A1,$B1)
=QUOTIENT($A1,$B1)
</syntaxhighlight>
</lang>


For remainder, type in G1
For remainder, type in G1
<lang excel>
<syntaxhighlight lang="excel">
=MOD($A1,$B1)
=MOD($A1,$B1)
</syntaxhighlight>
</lang>


For exponentiation, type in H1
For exponentiation, type in H1
<lang excel>
<syntaxhighlight lang="excel">
=$A1^$B1
=$A1^$B1
</syntaxhighlight>
</lang>

=={{header|F_Sharp|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:
<syntaxhighlight lang="fsharp">
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)
</syntaxhighlight>
For example, the output with the arguments 4 and 3 is:
<syntaxhighlight lang="fsharp">
4 + 3 = 7
4 - 3 = 1
4 * 3 = 12
4 / 3 = 1
4 % 3 = 1
</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: combinators io kernel math math.functions math.order
<syntaxhighlight lang="factor">USING: combinators io kernel math math.functions math.order
math.parser prettyprint ;
math.parser prettyprint ;


Line 1,013: Line 2,105:
[ gcd "gcd: " write . drop ]
[ gcd "gcd: " write . drop ]
[ lcm "lcm: " write . ]
[ lcm "lcm: " write . ]
} 2cleave</lang>
} 2cleave</syntaxhighlight>


{{out}}
output:
<pre>a=8

<lang factor>a=8
b=12
b=12
sum: 20
sum: 20
Line 1,029: Line 2,120:
minimum: 8
minimum: 8
gcd: 4
gcd: 4
lcm: 24</lang>
lcm: 24</pre>


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.
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.


=={{header|FALSE}}==
=={{header|FALSE}}==
<lang false>12 7
<syntaxhighlight lang="false">12 7
\$@$@$@$@$@$@$@$@$@$@\ { 6 copies }
\$@$@$@$@$@$@$@$@$@$@\ { 6 copies }
"sum = "+."
"sum = "+."
Line 1,041: Line 2,133:
quotient = "/."
quotient = "/."
modulus = "/*-."
modulus = "/*-."
"</lang>
"</syntaxhighlight>

=={{header|Fermat}}==
Integer division rounds towards zero; remainders are always positive regardless of the signs of the numbers.
<syntaxhighlight lang="fermat">
?a;
?b;
!!('Sum: a+b=',a+b);
!!('Difference: a-b=',a-b);
!!('Product: a*b=',a*b);
!!('Integer quotient: a\b=',a\b);
!!('Remainder: a|b=',a|b);
!!('Exponentiation: a^b=',a^b);
</syntaxhighlight>
{{out}}<pre>
>a := 64
>b := -5
Sum: a+b= 59
Difference: a-b= 69
Product: a*b= -320
Integer quotient: a\b= -12
Remainder: a|b= 4
Exponentiation: a^b= 1 / 1073741824
</pre>


=={{header|Forth}}==
=={{header|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 ).
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 ).
<lang forth>: arithmetic ( a b -- )
<syntaxhighlight lang="forth">: arithmetic ( a b -- )
cr ." a=" over . ." b=" dup .
cr ." a=" over . ." b=" dup .
cr ." a+b=" 2dup + .
cr ." a+b=" 2dup + .
Line 1,051: Line 2,166:
cr ." a*b=" 2dup * .
cr ." a*b=" 2dup * .
cr ." a/b=" /mod .
cr ." a/b=" /mod .
cr ." a mod b = " . cr ;</lang>
cr ." a mod b = " . cr ;</syntaxhighlight>


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.
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.


<lang forth>FM/MOD ( d n -- mod div ) \ floored
<syntaxhighlight lang="forth">FM/MOD ( d n -- mod div ) \ floored
SM/REM ( d n -- rem div ) \ symmetric
SM/REM ( d n -- rem div ) \ symmetric
M* ( n n -- d )</lang>
M* ( n n -- d )</syntaxhighlight>


In addition, there are unsigned variants.
In addition, there are unsigned variants.


<lang forth>UM/MOD ( ud u -- umod udiv )
<syntaxhighlight lang="forth">UM/MOD ( ud u -- umod udiv )
UM* ( u u -- ud )</lang>
UM* ( u u -- ud )</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
In ANSI FORTRAN 77 or later:
In ANSI FORTRAN 77 or later:
<lang fortran> INTEGER A, B
<syntaxhighlight lang="fortran"> INTEGER A, B
PRINT *, 'Type in two integer numbers separated by white space',
PRINT *, 'Type in two integer numbers separated by white space',
+ ' and press ENTER'
+ ' and press ENTER'
Line 1,079: Line 2,194:
+ 'exponentiation is an intrinsic op in Fortran, so...'
+ 'exponentiation is an intrinsic op in Fortran, so...'
PRINT *, ' A ** B = ', (A ** B)
PRINT *, ' A ** B = ', (A ** B)
END</lang>
END</syntaxhighlight>


=={{header|F_Sharp|F#}}==
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
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:
<lang fsharp>
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)
</lang>
For example, the output with the arguments 4 and 3 is:
<lang fsharp>
4 + 3 = 7
4 - 3 = 1
4 * 3 = 12
4 / 3 = 1
4 % 3 = 1
</lang>


Dim As Integer i, j
Input "Enter two integers separated by a comma"; i, j
Print i;" + "; j; " = "; i + j
Print i;" - "; j; " = "; i - j
Print i;" * "; j; " = "; i * j
Print i;" / "; j; " = "; i \ j
Print i;" % "; j; " = "; i Mod j
Print i;" ^ "; j; " = "; i ^ j
Sleep

' Integer division (for which FB uses the '\' operator) rounds towards zero

' Remainder (for which FB uses the Mod operator) will, if non-zero, match the sign
' of the first operand</syntaxhighlight>

Sample input and output:-
{{out}}
<pre>
Enter two integers separated by a comma? -12, 7
-12 + 7 = -5
-12 - 7 = -19
-12 * 7 = -84
-12 / 7 = -1
-12 % 7 = -5
-12 ^ 7 = -35831808
</pre>


=={{header|friendly interactive shell}}==
=={{header|friendly interactive shell}}==
<lang fishshell>
<syntaxhighlight lang="fishshell">
read a
read a
read b
read b
Line 1,109: Line 2,236:
echo 'a % b =' (math "$a % $b") # Remainder
echo 'a % b =' (math "$a % $b") # Remainder
echo 'a ^ b =' (math "$a ^ $b") # Exponentation
echo 'a ^ b =' (math "$a ^ $b") # Exponentation
</syntaxhighlight>
</lang>


=={{header|Frink}}==
=={{header|Frink}}==
This demonstrates normal division (which produces rational numbers when possible), <CODE>div</CODE>, and <CODE>mod</CODE>. <CODE>div</CODE> rounds toward negative infinity (defined as <CODE>floor[x/y]</CODE>). <CODE>mod</CODE> uses the sign of the second number (defined as <CODE>x - y * floor[x/y]</CODE>). All operators automatically produce big integers or exact rational numbers when necessary.
This demonstrates normal division (which produces rational numbers when possible), <CODE>div</CODE>, and <CODE>mod</CODE>. <CODE>div</CODE> rounds toward negative infinity (defined as <CODE>floor[x/y]</CODE>). <CODE>mod</CODE> uses the sign of the second number (defined as <CODE>x - y * floor[x/y]</CODE>). All operators automatically produce big integers or exact rational numbers when necessary.
<lang frink>
<syntaxhighlight lang="frink">
[a,b] = input["Enter numbers",["a","b"]]
[a,b] = input["Enter numbers",["a","b"]]
ops=["+", "-", "*", "/", "div" ,"mod" ,"^"]
ops=["+", "-", "*", "/", "div" ,"mod" ,"^"]
Line 1,121: Line 2,248:
println["$str = " + eval[str]]
println["$str = " + eval[str]]
}
}
</syntaxhighlight>
</lang>


{{out}}
Output is:
<lang frink>
<syntaxhighlight lang="frink">
10 + 20 = 30
10 + 20 = 30
10 - 20 = -10
10 - 20 = -10
Line 1,132: Line 2,259:
10 mod 20 = 10
10 mod 20 = 10
10 ^ 20 = 100000000000000000000
10 ^ 20 = 100000000000000000000
</syntaxhighlight>
</lang>

=={{header|FutureBasic}}==
Basic program
<syntaxhighlight lang="futurebasic">
window 1, @"Integer Arithmetic", ( 0, 0, 400, 300 )

NSInteger a = 25
NSInteger b = 53

print "addition "a" + "b" = " (a + b)
print "subtraction "a" - "b" = " (a - b)
print "multiplication "a" * "b" = " (a * b)
print "division "a" / "b" = " (a / b)
printf @"float division %ld / %ld = %f", a, b, (float)a / (float)b
print "modulo "a" % "b" = " (a mod b)
print "power "a" ^ "b" = " (a ^ b)

HandleEvents
</syntaxhighlight>

Output:
<pre>
addition: 25 + 53 = 78
subtraction: 25 - 53 = -28
multiplication: 25 * 53 = 1325
division: 25 / 53 = 0
float division: 25 / 53 = 0.471698
modulo: 25 mod 53 = 25
power: 25 ^ 53 = 1.232595e+74
</pre>

Standalone Intel, M1, M2 Macintosh application with user input
<syntaxhighlight lang="futurebasic">

_window = 1
begin enum 1
_int1Label
_int1Field
_int2Label
_int2Field
_calcResults
_calcBtn
end enum

void local fn BuildWindow
CGRect r

r = fn CGRectMake( 0, 0, 480, 360 )
window _window, @"Integer Arithmetic", r, NSWindowStyleMaskTitled + NSWindowStyleMaskClosable + NSWindowStyleMaskMiniaturizable

r = fn CGRectMake( 240, 320, 150, 24 )
textlabel _int1Label, @"Enter first integer:", r, _window
ControlSetAlignment( _int1Label, NSTextAlignmentRight )
r = fn CGRectMake( 400, 322, 60, 24 )
textfield _int1Field, YES, @"25", r, _window
ControlSetAlignment( _int1Field, NSTextAlignmentCenter )
ControlSetUsesSingleLineMode( _int1Field, YES )
ControlSetFormat( _int1Field, @"0123456789-", YES, 5, NULL )

r = fn CGRectMake( 240, 290, 150, 24 )
textlabel _int2Label, @"Enter second integer:", r, _window
ControlSetAlignment( _int2Label, NSTextAlignmentRight )
r = fn CGRectMake( 400, 292, 60, 24 )
textfield _int2Field, YES, @"53", r, _window
ControlSetAlignment( _int2Field, NSTextAlignmentCenter )
ControlSetUsesSingleLineMode( _int2Field, YES )
ControlSetFormat( _int2Field, @"0123456789-", YES, 5, NULL )

r = fn CGRectMake( 50, 60, 380, 200 )
textview _calcResults, r,,, _window
TextViewSetTextContainerInset( _calcResults, fn CGSizeMake( 10, 20 ) )
TextSetFontWithName( _calcResults, @"Menlo", 13.0 )
TextViewSetEditable( _calcResults, NO )

r = fn CGRectMake( 370, 13, 100, 32 )
button _calcBtn,,, @"Calculate", r
end fn

local fn PerformCalculations
CFStringRef tempStr

NSInteger i1 = fn ControlIntegerValue( _int1Field )
NSInteger i2 = fn ControlIntegerValue( _int2Field )

CFMutableStringRef mutStr = fn MutableStringWithCapacity( 0 )

// Display inout integers
tempStr = fn StringWithFormat( @"Number 1: %ld\nNumber 2: %ld\n\n", i1, i2 )
MutableStringAppendString( mutStr, tempStr )

// Add
tempStr = fn StringWithFormat( @"Addition: %ld + %ld = %ld\n", i1, i2, i1 + i2 )
MutableStringAppendString( mutStr, tempStr )

// Subtract
tempStr = fn StringWithFormat( @"Subtraction: %ld - %ld = %ld\n", i1, i2, i1 - i2 )
MutableStringAppendString( mutStr, tempStr )

// Multiply
tempStr = fn StringWithFormat( @"Multiplication: %ld * %ld = %ld\n", i1, i2, i1 * i2 )
MutableStringAppendString( mutStr, tempStr )

if ( i2 != 0 )

// Divide
tempStr = fn StringWithFormat( @"Integer Division: %ld / %ld = %ld\n", i1, i2, i1 / i2 )
MutableStringAppendString( mutStr, tempStr )

// Float Divide
tempStr = fn StringWithFormat( @"Float Division: %ld / %ld = %f\n", i1, i2, (float)i1 / (float)i2 )
MutableStringAppendString( mutStr, tempStr )

// mod
tempStr = fn StringWithFormat( @"Modulo: %ld mod %ld = %ld remainder\n", i1, i2, i1 mod i2 )
MutableStringAppendString( mutStr, tempStr )

// power
tempStr = fn StringWithFormat( @"Power: %ld ^ %ld = %e\n", i1, i2, i1 ^ i2 )
MutableStringAppendString( mutStr, tempStr )

else

MutableStringAppendString( mutStr, @"Cannot divide by zero." )

end if

TextSetString( _calcResults, mutStr )
end fn

void local fn DoDialog( ev as long, tag as long, wnd as long )
'~'1
select ( ev )
case _btnClick
select ( tag )
case _calcBtn : fn PerformCalculations
end select
case _windowWillClose : end
end select
end fn

on dialog fn DoDialog

fn BuildWindow

HandleEvents
</syntaxhighlight>

Output:
<pre>
Number 1: 25
Number 2: 53

Addition: 25 + 53 = 78
Subtraction: 25 - 53 = -28
Multiplication: 25 * 53 = 1325
Integer Division: 25 / 53 = 0
Float Division: 25 / 53 = 0.471698
Modulo: 25 mod 53 = 25 remainder
Power: 25 ^ 53 = 1.232595e+74
</pre>

=={{header|Gambas}}==
<syntaxhighlight lang="gambas">Public Sub Main()
Dim a, b As String
Dim c, d As Integer

Print "Enter two integer numbers, separated by space:"
Input a, b

c = CInt(a)
d = CInt(b)

Print "Sum: " & (c + d)
Print "Difference:" & (c - d)
Print "Product: " & (c * d)
Print "Integer: " & (c Div d)
Print "Remainder: " & (c Mod d)
Print "Exponentiation: " & (c ^ d)

End
</syntaxhighlight>
Output:
<pre>
Enter two integer numbers, separated by space:
8 1
Sum: 9
Difference:7
Product: 8
Integer: 8
Remainder: 0
Exponentiation: 8
</pre>


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap>run := function()
<syntaxhighlight lang="gap">run := function()
local a, b, f;
local a, b, f;
f := InputTextUser();
f := InputTextUser();
Line 1,149: Line 2,468:
Display(Concatenation(String(a), " ^ ", String(b), " = ", String(a ^ b)));
Display(Concatenation(String(a), " ^ ", String(b), " = ", String(a ^ b)));
CloseStream(f);
CloseStream(f);
end;</lang>
end;</syntaxhighlight>

=={{header|GDScript}}==
Requires Godot 4.

<syntaxhighlight lang="gdscript">
@tool
extends Node

@export var a: int:
set(value):
a = value
refresh()

@export var b: int:
set(value):
b = value
refresh()

# Output properties
@export var sum: int
@export var difference: int
@export var product: int
@export var integer_quotient: int
@export var remainder: int
@export var exponentiation: int
@export var divmod: int

func refresh():
sum = a + b
difference = a - b
product = a * b
integer_quotient = a / b # Rounds towards 0
remainder = a % b # Matches the sign of a
exponentiation = pow(a, b)
</syntaxhighlight>

=={{header|Genie}}==
Note: Using ''init:int'' and the ''return'' from the init block was introduced in release 0.43.92, February 2019.

<syntaxhighlight lang="genie">[indent=4]
/*
Arithmethic/Integer, in Genie
valac arithmethic-integer.gs
*/

init:int
a:int = 0
b:int = 0
if args.length > 2 do b = int.parse(args[2])
if args.length > 1 do a = int.parse(args[1])

print @"a+b: $a plus $b is $(a+b)"
print @"a-b: $a minus $b is $(a-b)"
print @"a*b: $a times $b is $(a*b)"
print @"a/b: $a by $b quotient is $(a/b) (rounded mode is TRUNCATION)"
print @"a%b: $a by $b remainder is $(a%b) (sign matches first operand)"

print "\nGenie does not include a raise to power operator"

return 0</syntaxhighlight>

{{out}}
<pre>prompt$ valac arithmetic-integer.gs
prompt$ ./arithmetic-integer -390 100
a+b: -390 plus 100 is -290
a-b: -390 minus 100 is -490
a*b: -390 times 100 is -39000
a/b: -390 by 100 quotient is -3 (rounded mode is TRUNCATION)
a%b: -390 by 100 remainder is -90 (sign matches first operand)

Genie does not include a raise to power operator</pre>


=={{header|GEORGE}}==
=={{header|GEORGE}}==
<lang GEORGE>R (m) ;
<syntaxhighlight lang="george">R (m) ;
R (n) ;
R (n) ;
m n + P;
m n + P;
Line 1,158: Line 2,548:
m n × P;
m n × P;
m n div P;
m n div P;
m n rem P;</lang>
m n rem P;</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
===int===
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 1,175: Line 2,566:
fmt.Printf("%d %% %d = %d\n", a, b, a%b) // same sign as first operand
fmt.Printf("%d %% %d = %d\n", a, b, a%b) // same sign as first operand
// no exponentiation operator
// no exponentiation operator
}</lang>
}</syntaxhighlight>
Example run:
{{out|Example run}}
<pre>
<pre>
enter two integers: -5 3
enter two integers: -5 3
Line 1,185: Line 2,576:
-5 % 3 = -2
-5 % 3 = -2
</pre>
</pre>
===big.Int===
<syntaxhighlight lang="go">package main

import (
"fmt"
"math/big"
)

func main() {
var a, b, c big.Int
fmt.Print("enter two integers: ")
fmt.Scan(&a, &b)
fmt.Printf("%d + %d = %d\n", &a, &b, c.Add(&a, &b))
fmt.Printf("%d - %d = %d\n", &a, &b, c.Sub(&a, &b))
fmt.Printf("%d * %d = %d\n", &a, &b, c.Mul(&a, &b))

// Quo, Rem functions work like Go operators on int:
// quo truncates toward 0,
// and a non-zero rem has the same sign as the first operand.
fmt.Printf("%d quo %d = %d\n", &a, &b, c.Quo(&a, &b))
fmt.Printf("%d rem %d = %d\n", &a, &b, c.Rem(&a, &b))

// Div, Mod functions do Euclidean division:
// the result m = a mod b is always non-negative,
// and for d = a div b, the results d and m give d*y + m = x.
fmt.Printf("%d div %d = %d\n", &a, &b, c.Div(&a, &b))
fmt.Printf("%d mod %d = %d\n", &a, &b, c.Mod(&a, &b))

// as with int, no exponentiation operator
}</syntaxhighlight>
{{out|Example run}}
<pre>
enter two integers: -5 3
-5 + 3 = -2
-5 - 3 = -8
-5 * 3 = -15
-5 quo 3 = -1
-5 rem 3 = -2
-5 div 3 = -2
-5 mod 3 = 1
</pre>

=={{header|Golfscript}}==
Quotients round towards negative infinity. Remainders match the sign of the second operand.
<syntaxhighlight lang="golfscript">n/~~:b;~:a;a b+n a b-n a b*n a b/n a b%n a b?</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
'''Solution:'''
<lang groovy>def arithmetic = { a, b ->
<syntaxhighlight lang="groovy">def arithmetic = { a, b ->
println """
println """
a + b = ${a} + ${b} = ${a + b}
a + b = ${a} + ${b} = ${a + b}
Line 1,200: Line 2,637:
a ** b = ${a} ** ${b} = ${a ** b}
a ** b = ${a} ** ${b} = ${a ** b}
"""
"""
}</lang>
}</syntaxhighlight>


'''Test:'''
Program:
<lang groovy>arithmetic(5,3)</lang>
<syntaxhighlight lang="groovy">arithmetic(5,3)</syntaxhighlight>


{{out}}
Output:
<pre> a + b = 5 + 3 = 8
<pre> a + b = 5 + 3 = 8
a - b = 5 - 3 = 2
a - b = 5 - 3 = 2
Line 1,218: Line 2,655:


=={{header|Harbour}}==
=={{header|Harbour}}==
<lang visualfoxpro>procedure Test( a, b )
<syntaxhighlight lang="visualfoxpro">procedure Test( a, b )
? "a+b", a + b
? "a+b", a + b
? "a-b", a - b
? "a-b", a - b
Line 1,228: Line 2,665:
// Exponentiation is also a base arithmetic operation
// Exponentiation is also a base arithmetic operation
? "a**b", a ** b
? "a**b", a ** b
return</lang>
return</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==


<lang haskell>main = do
<syntaxhighlight lang="haskell">main = do
a <- readLn :: IO Integer
a <- readLn :: IO Integer
b <- readLn :: IO Integer
b <- readLn :: IO Integer
Line 1,246: Line 2,683:
putStrLn $ "a `quot` b = " ++ show (a `quot` b) -- truncates towards 0
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 `rem` b = " ++ show (a `rem` b) -- same sign as first operand
putStrLn $ "a `quotRem` b = " ++ show (a `quotRem` b)</lang>
putStrLn $ "a `quotRem` b = " ++ show (a `quotRem` b)</syntaxhighlight>


=={{header|Haxe}}==
=={{header|Haxe}}==
<lang haxe>class BasicIntegerArithmetic {
<syntaxhighlight lang="haxe">class BasicIntegerArithmetic {
public static function main() {
public static function main() {
var args =Sys.args();
var args =Sys.args();
Line 1,261: Line 2,698:
trace("a%b = " + (a%b));
trace("a%b = " + (a%b));
}
}
}</lang>
}</syntaxhighlight>


=={{header|HicEst}}==
=={{header|HicEst}}==
All numeric is 8-byte-float. Conversions are by INT, NINT, FLOOR, CEILING, or Formatted IO
All numeric is 8-byte-float. Conversions are by INT, NINT, FLOOR, CEILING, or Formatted IO
<lang hicest>DLG(Edit=A, Edit=B, TItle='Enter numeric A and B')
<syntaxhighlight lang="hicest">DLG(Edit=A, Edit=B, TItle='Enter numeric A and B')
WRITE(Name) A, B
WRITE(Name) A, B
WRITE() ' A + B = ', A + B
WRITE() ' A + B = ', A + B
Line 1,277: Line 2,714:
WRITE() 'remainder of A / B = ', MOD(A, B) ! same sign as A
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
WRITE() 'A to the power of B = ', A ** B</lang>
WRITE() 'A to the power of B = ', A ** B</syntaxhighlight>
<lang hicest>A=5; B=-4;
<syntaxhighlight lang="hicest">A=5; B=-4;
A + B = 1
A + B = 1
A - B = 9
A - B = 9
Line 1,289: Line 2,726:
remainder of A / B = 1
remainder of A / B = 1
A to the power of B = 16E-4
A to the power of B = 16E-4
A to the power of B = 16E-4 </lang>
A to the power of B = 16E-4 </syntaxhighlight>

=={{header|HolyC}}==
<syntaxhighlight lang="holyc">I64 *a, *b;
a = Str2I64(GetStr("Enter your first number: "));
b = Str2I64(GetStr("Enter your second number: "));

if (b == 0)
Print("Error: The second number must not be zero.\n");
else {
Print("a + b = %d\n", a + b);
Print("a - b = %d\n", a - b);
Print("a * b = %d\n", a * b);
Print("a / b = %d\n", a / b); /* rounds down */
Print("a % b = %d\n", a % b); /* same sign as first operand */
Print("a ` b = %d\n", a ` b);
}</syntaxhighlight>

=={{header|i}}==
<syntaxhighlight lang="i">main
a $= integer(in(' ')); ignore
b $= integer(in('\n')); ignore
print("Sum:" , a + b)
print("Difference:", a - b)
print("Product:" , a * b)
print("Quotient:" , a / b) // rounds towards zero
print("Modulus:" , a % b) // same sign as first operand
print("Exponent:" , a ^ b)
}</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<lang Icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
writes("Input 1st integer a := ")
writes("Input 1st integer a := ")
a := integer(read())
a := integer(read())
Line 1,304: Line 2,770:
write(" a % b = ",a%b, " remainder sign matches a")
write(" a % b = ",a%b, " remainder sign matches a")
write(" a ^ b = ",a^b)
write(" a ^ b = ",a^b)
end</lang>
end</syntaxhighlight>


=={{header|Inform 7}}==
=={{header|Inform 7}}==


<lang inform7>Enter Two Numbers is a room.
<syntaxhighlight lang="inform7">Enter Two Numbers is a room.


Numerically entering is an action applying to one number. Understand "[number]" as numerically entering.
Numerically entering is an action applying to one number. Understand "[number]" as numerically entering.
Line 1,331: Line 2,797:
Equation - Division Formula
Equation - Division Formula
Q = A / B
Q = A / B
where Q is a number, A is a number, and B is a number.</lang>
where Q is a number, A is a number, and B is a number.</syntaxhighlight>


This solution shows four syntaxes: mathematical operators, English operators, inline equations, and named equations. Division rounds toward zero, and the remainder has the same sign as the quotient.
This solution shows four syntaxes: mathematical operators, English operators, inline equations, and named equations. Division rounds toward zero, and the remainder has the same sign as the quotient.


=={{header|J}}==
=={{header|J}}==
<lang j>calc =: + , - , * , <.@% , |~ , ^</lang>
<syntaxhighlight lang="j">calc =: + , - , * , <.@% , |~ , ^</syntaxhighlight>
The function <code>calc</code> constructs a list of numeric results for this task.
The function <code>calc</code> constructs a list of numeric results for this task. The implementation of integer division we use here (<code><.@%.</code>) rounds down (towards negative infinity), and this is compatible with the remainder implementation we use here.
<lang j> 17 calc 3
<syntaxhighlight lang="j"> 17 calc 3
20 14 51 5 2 4913</lang>
20 14 51 5 2 4913</syntaxhighlight>


The function <code>bia</code> assembles these results, textually:
The function <code>bia</code> assembles these results, textually:


<lang j>labels =: ];.2 'Sum: Difference: Product: Quotient: Remainder: Exponentiation: '
<syntaxhighlight lang="j">labels =: ];.2 'Sum: Difference: Product: Quotient: Remainder: Exponentiation: '
combine =: ,. ":@,.
combine =: ,. ":@,.
bia =: labels combine calc
bia =: labels combine calc
Line 1,353: Line 2,819:
Quotient: 5
Quotient: 5
Remainder: 2
Remainder: 2
Exponentiation: 4913</lang>
Exponentiation: 4913</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
<lang java>import java.util.Scanner;
<syntaxhighlight lang="java">import java.util.Scanner;

public class Int{
public static void main(String[] args){
public class IntegerArithmetic {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Get the 2 numbers from command line arguments
int a = sc.nextInt();
int b = sc.nextInt();
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);
int sum = a + b; // The result of adding 'a' and 'b' (Note: integer addition is discouraged in print statements due to confusion with string concatenation)
System.out.println("a - b = " + (a - b));
int difference = a - b; // The result of subtracting 'b' from 'a'
System.out.println("a * b = " + (a * b));
int product = a * b; // The result of multiplying 'a' and 'b'
System.out.println("quotient of a / b = " + (a / b)); // truncates towards 0
int division = a / b; // The result of dividing 'a' by 'b' (Note: 'division' does not contain the fractional result)
System.out.println("remainder of a / b = " + (a % b)); // same sign as first operand
int remainder = a % b; // The remainder of dividing 'a' by 'b'
}

}</lang>
System.out.println("a + b = " + sum);
System.out.println("a - b = " + difference);
System.out.println("a * b = " + product);
System.out.println("quotient of a / b = " + division); // truncates towards 0
System.out.println("remainder of a / b = " + remainder); // same sign as first operand
}
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
===WScript===
{{works with|JScript}}
{{works with|JScript}}
{{works with|SpiderMonkey}}
{{works with|SpiderMonkey}}
Note that the operators work the same in all versions of JavaScript; the requirement for specific implementations is in order to get user input.
Note that the operators work the same in all versions of JavaScript; the requirement for specific implementations is in order to get user input.
<lang javascript>var a = parseInt(get_input("Enter an integer"), 10);
<syntaxhighlight lang="javascript">var a = parseInt(get_input("Enter an integer"), 10);
var b = parseInt(get_input("Enter an integer"), 10);
var b = parseInt(get_input("Enter an integer"), 10);


Line 1,401: Line 2,875:
print(prompt);
print(prompt);
}
}
}</lang>
}</syntaxhighlight>
{{out}}
output:
<pre>Enter an integer
<pre>Enter an integer
-147
-147
Line 1,414: Line 2,888:
quotient: a / b = -2
quotient: a / b = -2
remainder: a % b = -21</pre>
remainder: a % b = -21</pre>
===Node.JS===
<syntaxhighlight lang="javascript">// Invoked as node script_name.js <a> <b>. Positions 0 and 1 in the argv array contain 'node' and 'script_name.js' respectively
var a = parseInt(process.argv[2], 10);
var b = parseInt(process.argv[3], 10);

var sum = a + b;
var difference = a - b;
var product = a * b;
var division = a / b;
var remainder = a % b; // This produces the remainder after dividing 'b' into 'a'. The '%' operator is called the 'modulo' operator

console.log('a + b = %d', sum); // The %d syntax is a placeholder that is replaced by the sum
console.log('a - b = %d', difference);
console.log('a * b = %d', product);
console.log('a / b = %d', division);
console.log('a % b = %d', remainder);</syntaxhighlight>
{{out}}
<pre>$ node arith.js 10 7
a + b = 17
a - b = 3
a * b = 70
a / b = 1.4285714285714286
a % b = 3</pre>


=={{header|jq}}==
=={{header|jq}}==
<lang jq># Lines which do not have two integers are skipped:
<syntaxhighlight lang="jq"># Lines which do not have two integers are skipped:


def arithmetic:
def arithmetic:
Line 1,433: Line 2,930:


arithmetic
arithmetic
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,463: Line 2,960:
a % b = -2
a % b = -2
a | exp = 0.1353352832366127</pre>
a | exp = 0.1353352832366127</pre>

=={{header|Jsish}}==
<syntaxhighlight lang="javascript">"use strict";
/* Arthimetic/Integer, in Jsish */
var line = console.input();
var nums = line.match(/^\s*([+-]?[0-9]+)\s+([+-]?[0-9]+)\s*/);
var a = Number(nums[1]);
var b = Number(nums[2]);

puts("A is ", a, ", B is ", b);
puts("Sum A + B is ", a + b);
puts("Difference A - B is ", a - b);
puts("Product A * B is ", a * b);
puts("Integer quotient A / B is ", a / b | 0, " truncates toward 0");
puts("Remainder A % B is ", a % b, " sign follows first operand");
puts("Exponentiation A to the power B is ", Math.pow(a, b));

/*
=!INPUTSTART!=
7 4
=!INPUTEND!=
*/


/*
=!EXPECTSTART!=
A is 7 , B is 4
Sum A + B is 11
Difference A - B is 3
Product A * B is 28
Integer quotient A / B is 1 truncates toward 0
Remainder A % B is 3 sign follows first operand
Exponentiation A to the power B is 2401
=!EXPECTEND!=
*/</syntaxhighlight>

{{out}}
<pre>prompt$ jsish -u arithmeticInteger.jsi
[PASS] arithmeticInteger.jsi</pre>


=={{header|Julia}}==
=={{header|Julia}}==
<lang Julia>function arithmetic (a = int(readline()), b = int(readline()))
<syntaxhighlight lang="julia">function arithmetic (a = parse(Int, readline()), b = parse(Int, readline()))
for op in [+,-,*,div,rem]
for op in [+,-,*,div,rem]
println("a $op b = $(op(a,b))")
println("a $op b = $(op(a,b))")
end
end
end</lang>
end</syntaxhighlight>
{{Out}}
{{Out}}
<pre>julia> arithmetic()
<pre>julia> arithmetic()
Line 1,479: Line 3,015:
a div b = 0
a div b = 0
a rem b = 4</pre>
a rem b = 4</pre>

=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">
import kotlin.math.pow // not an operator but in the standard library

fun main() {
val r = Regex("""-?[0-9]+\s+-?[0-9]+""")
print("Enter two integers separated by space(s): ")
val input: String = readLine()!!.trim()
val index = input.lastIndexOf(' ')
val a = input.substring(0, index).trimEnd().toLong()
val b = input.substring(index + 1).toLong()
println("$a + $b = ${a + b}")
println("$a - $b = ${a - b}")
println("$a * $b = ${a * b}")
println("$a / $b = ${a / b}") // rounds towards zero
println("$a % $b = ${a % b}") // if non-zero, matches sign of first operand
println("$a ^ $b = ${a.toDouble().pow(b.toDouble())}")
}
}</syntaxhighlight>

{{out}}
<pre>
Enter two integers separated by space(s): 2 63
2 + 63 = 65
2 - 63 = -61
2 * 63 = 126
2 / 63 = 0
2 % 63 = 2
2 ^ 63 = 9.223372036854776E18
</pre>


=={{header|LabVIEW}}==
=={{header|LabVIEW}}==
Line 1,484: Line 3,051:
[[File:LabVIEW_Arithmetic_Integer.png]]
[[File:LabVIEW_Arithmetic_Integer.png]]


=={{header|Lambdatalk}}==
Translation of Racket
<syntaxhighlight lang="scheme">
{def arithmetic
{lambda {:x :y}
{S.map {{lambda {:x :y :op}
{br}applying :op on :x & :y returns {:op :x :y}} :x :y}
+ - * / % pow max min = > <}}}
-> arithmetic


{arithmetic 8 12}
->
applying + on 8 & 12 returns 20
applying - on 8 & 12 returns -4
applying * on 8 & 12 returns 96
applying / on 8 & 12 returns 0.6666666666666666
applying % on 8 & 12 returns 8
applying pow on 8 & 12 returns 68719476736
applying max on 8 & 12 returns 12
applying min on 8 & 12 returns 8
applying = on 8 & 12 returns false
applying > on 8 & 12 returns false
applying < on 8 & 12 returns true
</syntaxhighlight>


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>local(a = 6, b = 4)
<syntaxhighlight lang="lasso">local(a = 6, b = 4)
#a + #b // 10
#a + #b // 10
#a - #b // 2
#a - #b // 2
Line 1,494: Line 3,084:
#a % #b // 2
#a % #b // 2
math_pow(#a,#b) // 1296
math_pow(#a,#b) // 1296
math_pow(#b,#a) // 4096</lang>
math_pow(#b,#a) // 4096</syntaxhighlight>

=={{header|LDPL}}==
<syntaxhighlight lang="ldpl">data:
x is number
y is number
result is number

procedure:
display "Enter x: "
accept x
display "Enter y: "
accept y
add x and y in result
display "x + y = " result lf
subtract y from x in result
display "x - y = " result lf
multiply x by y in result
display "x * y = " result lf
divide x by y in result # There is no integer division but
floor result # floor rounds toward negative infinity
display "x / y = " result lf
modulo x by y in result
display "x % y = " result lf # Returns the sign of the 2nd argument
raise x to y in result
display "x ^ y = " result lf</syntaxhighlight>
{{out}}
<pre>
Enter x: 13
Enter y: 4
x + y = 17
x - y = 9
x * y = 52
x / y = 3
x % y = 1
x ^ y = 28561
</pre>


=={{header|LFE}}==
=={{header|LFE}}==


<lang lisp>
<syntaxhighlight lang="lisp">
(defmodule arith
(defmodule arith
(export all))
(export all))
Line 1,513: Line 3,139:
; rem's result takes the same sign as the first operand
; rem's result takes the same sign as the first operand
(: io format '"~p rem ~p = ~p~n" (list a b (rem a b))))))
(: io format '"~p rem ~p = ~p~n" (list a b (rem a b))))))
</syntaxhighlight>
</lang>


Usage from the LFE REPL:
Usage from the LFE REPL:
<lang lisp>
<syntaxhighlight lang="lisp">
> (slurp '"arith.lfe")
> (slurp '"arith.lfe")
#(ok arith)
#(ok arith)
Line 1,528: Line 3,154:
2 rem 8 = 2
2 rem 8 = 2
ok
ok
</syntaxhighlight>
</lang>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
Note that raising to a power can display very large integers without going to approximate power-of-ten notation.
Note that raising to a power can display very large integers without going to approximate power-of-ten notation.
<syntaxhighlight lang="lb">
<lang lb>
input "Enter the first integer: "; first
input "Enter the first integer: "; first
input "Enter the second integer: "; second
input "Enter the second integer: "; second
Line 1,542: Line 3,168:
print "The remainder is " ; first MOD second; " (sign matches first operand)"
print "The remainder is " ; first MOD second; " (sign matches first operand)"
print "The first raised to the power of the second is " ; first ^second
print "The first raised to the power of the second is " ; first ^second
</syntaxhighlight>
</lang>

=={{header|LIL}}==
<syntaxhighlight lang="tcl"># Arithmetic/Integer, in LIL
write "Enter two numbers separated by space: "
if {[canread]} {set line [readline]}
print

set a [index $line 0]
set b [index $line 1]
print "A is $a"", B is $b"
print "Sum A + B is [expr $a + $b]"
print "Difference A - B is [expr $a - $b]"
print "Product A * B is [expr $a * $b]"
print "Integer Quotient A \\ B is [expr $a \ $b], truncates toward zero"
print "Remainder A % B is [expr $a % $b], sign follows first operand"
print "LIL has no exponentiation expression operator"</syntaxhighlight>

{{out}}
<pre>prompt$ echo '7 4' | lil arithmeticInteger.lil
Enter two numbers separated by space:
A is 7, B is 4
Sum A + B is 11
Difference A - B is 3
Product A * B is 28
Integer Quotient A \ B is 1, truncates toward zero
Remainder A % B is 3, sign follows first operand
LIL has no exponentiation expression operator

prompt$ echo '-7 4' | lil arithmeticInteger.lil
Enter two numbers separated by space:
A is -7, B is 4
Sum A + B is -3
Difference A - B is -11
Product A * B is -28
Integer Quotient A \ B is -1, truncates toward zero
Remainder A % B is -3, sign follows first operand
LIL has no exponentiation expression operator</pre>

=={{header|Lingo}}==
<syntaxhighlight lang="lingo">-- X, Y: 2 editable field members, shown as sprites in the current GUI
x = integer(member("X").text)
y = integer(member("Y").text)

put "Sum: " , x + y
put "Difference: ", x - y
put "Product: " , x * y
put "Quotient: " , x / y -- Truncated towards zero
put "Remainder: " , x mod y -- Result has sign of left operand
put "Exponent: " , power(x, y)</syntaxhighlight>

=={{header|Little}}==
<syntaxhighlight lang="c"># Maybe you need to import the mathematical funcions
# from Tcl with:
# eval("namespace path ::tcl::mathfunc");

void main() {
int a, b;
puts("Enter two integers:");
a = (int)(gets(stdin));
b = (int)(gets(stdin));
puts("${a} + ${b} = ${a+b}");
puts("${a} - ${b} = ${a-b}");
puts("${a} * ${b} = ${a*b}");
puts("${a} / ${b} = ${a/b}, remainder ${a%b}");
puts("${a} to the power of ${b} = ${(int)pow(a,b)}");
}</syntaxhighlight>

=={{header|LiveCode}}==
<syntaxhighlight lang="livecode">ask "enter 2 numbers (comma separated)"
if it is not empty then
put item 1 of it into n1
put item 2 of it into n2
put sum(n1,n2) into ai["sum"]
put n1 * n2 into ai["product"]
put n1 div n2 into ai["quotient"] -- truncates
put n1 mod n2 into ai["remainder"]
put n1^n2 into ai["power"]
combine ai using comma and colon
put ai
end if</syntaxhighlight>
Examples<syntaxhighlight lang="text">-2,4 - power:16,product:-8,quotient:0,remainder:-2,sum:2
2,-4 - power:0.0625,product:-8,quotient:0,remainder:2,sum:-2
-2,-4 - power:0.0625,product:8,quotient:0,remainder:-2,sum:-6
2,4 - power:16,product:8,quotient:0,remainder:2,sum:6
11,4 - power:14641,product:44,quotient:2,remainder:3,sum:15</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>to operate :a :b
<syntaxhighlight lang="logo">to operate :a :b
(print [a =] :a)
(print [a =] :a)
(print [b =] :b)
(print [b =] :b)
Line 1,553: Line 3,264:
(print [a / b =] int :a / :b)
(print [a / b =] int :a / :b)
(print [a mod b =] modulo :a :b)
(print [a mod b =] modulo :a :b)
end</lang>
end</syntaxhighlight>


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.
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.


=={{header|LSE64}}==
=={{header|LSE64}}==
<lang lse64>over : 2 pick
<syntaxhighlight lang="lse64">over : 2 pick
2dup : over over
2dup : over over


Line 1,567: Line 3,278:
" A*B=" ,t 2dup * , nl \
" A*B=" ,t 2dup * , nl \
" A/B=" ,t 2dup / , nl \
" A/B=" ,t 2dup / , nl \
" A%B=" ,t % , nl</lang>
" A%B=" ,t % , nl</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>local x = io.read()
<syntaxhighlight lang="lua">local x = io.read()
local y = io.read()
local y = io.read()


Line 1,578: Line 3,289:
print ("Quotient: " , (x / y)) -- Does not truncate
print ("Quotient: " , (x / y)) -- Does not truncate
print ("Remainder: " , (x % y)) -- Result has sign of right operand
print ("Remainder: " , (x % y)) -- Result has sign of right operand
print ("Exponent: " , (x ^ y))</lang>
print ("Exponent: " , (x ^ y))</syntaxhighlight>

=={{header|M2000 Interpreter}}==
We can use variables with %, which are double inside with no decimal part. These can have 17 digits. Also A%=1.5 make it 2, not 1. This has a tricky situation: A%=1/2 give 1 to A%. We can use FLOOR() or INT() is the same, or CEIL(), and there is a BANK() which is a Banker Round: BANK(2.5)=2 and BANK(3.5)=4.




<syntaxhighlight lang="m2000 interpreter">
MODULE LikeCommodoreBasic {
\\ ADDITION: EUCLIDEAN DIV# & MOD# AND ** FOR POWER INCLUDING ^
10 INPUT "ENTER A NUMBER:"; A%
20 INPUT "ENTER ANOTHER NUMBER:"; B%
30 PRINT "ADDITION:";A%;"+";B%;"=";A%+B%
40 PRINT "SUBTRACTION:";A%;"-";B%;"=";A%-B%
50 PRINT "MULTIPLICATION:";A%;"*";B%;"=";A%*B%
60 PRINT "INTEGER DIVISION:";A%;"DIV";B%;"=";A% DIV B%
65 PRINT "INTEGER EUCLIDEAN DIVISION:";A%;"DIV";B%;"=";A% DIV# B%
70 PRINT "REMAINDER OR MODULO:";A%;"MOD";B%;"=";A% MOD B%
75 PRINT "EUCLIDEAN REMAINDER OR MODULO:";A%;"MOD#";B%;"=";A% MOD# B%
80 PRINT "POWER:";A%;"^";B%;"=";A%^B%
90 PRINT "POWER:";A%;"**";B%;"=";A%**B%
}
LikeCommodoreBasic


Module IntegerTypes {
a=12% ' Integer 16 bit
b=12& ' Long 32 bit
c=12@' Decimal (29 digits)
Def ExpType$(x)=Type$(x)
Print ExpType$(a+1)="Double"
Print ExpType$(a+1%)="Integer"
Print ExpType$(a div 5)="Double"
Print ExpType$(a div 5%)="Double"
Print ExpType$(a mod 5)="Double"
Print ExpType$(a mod 5%)="Double"
Print ExpType$(a**2)="Double"
Print ExpType$(b+1)="Double"
Print ExpType$(b+1&)="Long"
Print ExpType$(b div 5)="Double"
Print ExpType$(b div 5&)="Double"
Print ExpType$(b mod 5)="Double"
Print ExpType$(b mod 5&)="Double"
Print ExpType$(b**2)="Double"

Print ExpType$(c+1)="Decimal"
Print ExpType$(c+1@)="Decimal"
Print ExpType$(c div 5)="Decimal"
Print ExpType$(c div 5@)="Decimal"
Print ExpType$(c mod 5)="Decimal"
Print ExpType$(c mod 5@)="Decimal"
Print ExpType$(c**2)="Double"
}
IntegerTypes
</syntaxhighlight>


=={{header|M4}}==
=={{header|M4}}==


Because of the particular nature of M4, the only user-input is the code itself. Anyway the following code can be used:
Because of the particular nature of M4, the only user-input is the code itself. Anyway the following code can be used:
<lang m4>eval(A+B)
<syntaxhighlight lang="m4">eval(A+B)
eval(A-B)
eval(A-B)
eval(A*B)
eval(A*B)
eval(A/B)
eval(A/B)
eval(A%B)</lang>
eval(A%B)</syntaxhighlight>


once saved in a file, e.g. <tt>operations.m4</tt>:
once saved in a file, e.g. <tt>operations.m4</tt>:
Line 1,595: Line 3,362:
or using a sort of ''driver'':
or using a sort of ''driver'':


<lang m4>define(`A', 4)dnl
<syntaxhighlight lang="m4">define(`A', 4)dnl
define(`B', 6)dnl
define(`B', 6)dnl
include(`operations.m4')</lang>
include(`operations.m4')</syntaxhighlight>


=={{header|Maple}}==
=={{header|Maple}}==
These operations are all built-in. As all operations are exact, there are no rounding issues involved.
These operations are all built-in. As all operations are exact, there are no rounding issues involved.
<syntaxhighlight lang="maple">
<lang Maple>
DoIt := proc()
DoIt := proc()
local a := readstat( "Input an integer: " ):
local a := readstat( "Input an integer: " ):
Line 1,612: Line 3,379:
NULL # quiet return
NULL # quiet return
end proc:
end proc:
</syntaxhighlight>
</lang>
Here is an example of calling DoIt.
Here is an example of calling DoIt.
<syntaxhighlight lang="maple">
<lang Maple>
> DoIt();
> DoIt();
Input an integer: 15;
Input an integer: 15;
Line 1,624: Line 3,391:
Remainder = 3
Remainder = 3
>
>
</syntaxhighlight>
</lang>


=={{header|Mathematica}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Mathematica has all the function built-in to handle this task. Example:
Mathematica has all the function built-in to handle this task. Example:
<lang Mathematica>a = Input["Give me an integer please!"];
<syntaxhighlight lang="mathematica">a = Input["Give me an integer please!"];
b = Input["Give me another integer please!"];
b = Input["Give me another integer please!"];
Print["You gave me ", a, " and ", b];
Print["You gave me ", a, " and ", b];
Line 1,634: Line 3,401:
Print["difference: ", a - b];
Print["difference: ", a - b];
Print["product: ", a b];
Print["product: ", a b];
Print["integer quotient: ", IntegerPart[a/b]];
Print["integer quotient: ", Quotient[a, b]];
Print["remainder: ", Mod[a, b]];
Print["remainder: ", Mod[a, b]];
Print["exponentiation: ", a^b];</lang>
Print["exponentiation: ", a^b];</syntaxhighlight>
gives back for input 17 and 3:
gives back for input 17 and 3:
<preMathematica>You gave me 17 and 3
<pre>You gave me 17 and 3
sum: 20
sum: 20
difference: 14
difference: 14
Line 1,645: Line 3,412:
remainder: 2
remainder: 2
exponentiation: 4913</pre>
exponentiation: 4913</pre>

=={{header|Mathcad}}==
The text below (from "Task Notes" onwards) is pretty well what you will see on a Mathcad worksheet across most versions (eg, Mathcad 15, Mathcad Prime 6.0, and Mathcad Prime 6.0 Express). Mathcad's "whiteboard" interface allows the user to mix formatted text regions with formatted math regions. Text region formatting is fairly arbitrary, individual characters can have their font, font size and bold/italic/underline settings set or changed at will. Math regions use amendable styles to identify variables, functions (normally built-in functions), keywords, system words and units (Mathcad has a units-aware, SI-based quantity system). It really is a simple as 'writing' on the whiteboard.

----

'''Task Notes'''

''For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).''

There is no quotient function in Mathcad, only complex division. We emulate quotient by standard division followed by rounding using both floor, which rounds towards negative infinity, and trunc, which rounds towards zero.

''For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
''
We use the Mathcad function mod(x,y), which returns x modulo y, and has the same sign as x.

'''Instructions'''

Enter two integers of your choice for Int1 and Int2.

(type into the right hand side of the 'Int1:= ' and 'Int2:=' statements, overwriting or modifying any numbers already there)

'''Implementation'''

'''Mathcad Input and Output'''

Mathcad "standard" input and output takes place directly on a worksheet ("program source code").

'''Inputs''':

== ''the user types in values after := (definition) operator''

Integer One: ''Int1'':='''-8'''

Integer Two: ''Int2'':='''3'''

'''Results''':

== ''Mathcad automatically calculates and displays results after = (evaluation) operator.''

sum : ''Int1'' + ''Int2'' = -5

difference : ''Int1'' - ''Int2'' = -11

product : ''Int1'' · ''Int2'' = -24

integer quotient : floor(''Int1''÷''Int2'')=-3 trunc(Int1÷Int2)=-2

remainder : mod(''Int1'',''Int2'')=-2

exponentiation : ''Int1''<sup>''Int2''</sup>=-512

----


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
<lang octave>disp("integer a: "); a = scanf("%d", 1);
<syntaxhighlight lang="octave">disp("integer a: "); a = scanf("%d", 1);
disp("integer b: "); b = scanf("%d", 1);
disp("integer b: "); b = scanf("%d", 1);
a+b
a+b
Line 1,654: Line 3,474:
floor(a/b)
floor(a/b)
mod(a,b)
mod(a,b)
a^b</lang>
a^b</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>block(
<syntaxhighlight lang="maxima">block(
[a: read("a"), b: read("b")],
[a: read("a"), b: read("b")],
print(a + b),
print(a + b),
Line 1,666: Line 3,486:
print(remainder(a, b)),
print(remainder(a, b)),
a^b
a^b
);</lang>
);</syntaxhighlight>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
<lang maxscript>x = getKBValue prompt:"First number"
<syntaxhighlight lang="maxscript">x = getKBValue prompt:"First number"
y = getKBValue prompt:"Second number:"
y = getKBValue prompt:"Second number:"


Line 1,676: Line 3,496:
format "Product: %\n" (x * y)
format "Product: %\n" (x * y)
format "Quotient: %\n" (x / y)
format "Quotient: %\n" (x / y)
format "Remainder: %\n" (mod x y)</lang>
format "Remainder: %\n" (mod x y)</syntaxhighlight>


=={{header|Mercury}}==
=={{header|Mercury}}==
<lang>
<syntaxhighlight lang="text">
:- module arith_int.
:- module arith_int.
:- interface.
:- interface.
Line 1,722: Line 3,542:
io.set_exit_status(1, !IO)
io.set_exit_status(1, !IO)
).
).
</syntaxhighlight>
</lang>


=={{header|Metafont}}==
=={{header|Metafont}}==


<lang metafont>string s[];
<syntaxhighlight lang="metafont">string s[];
message "input number a: ";
message "input number a: ";
s1 := readstring;
s1 := readstring;
Line 1,743: Line 3,563:
outp("mod");
outp("mod");


end</lang>
end</syntaxhighlight>

=={{header|min}}==
{{works with|min|0.37.0}}
<syntaxhighlight lang="min">('+ '- '* 'div 'mod)
(("Enter an integer" ask integer) 2 times) quote-map =>
("$1 -> $2" rollup concat dup -> quote prepend %) prepend
map "\n" join puts!</syntaxhighlight>
{{out}}
<pre>
Enter an integer: -3
Enter an integer: 5
(-3 5 +) -> 2
(-3 5 -) -> -8
(-3 5 *) -> -15
(-3 5 div) -> 0
(-3 5 mod) -> -3
</pre>


=={{header|МК-61/52}}==
=={{header|МК-61/52}}==
<lang>П1 <-> П0
<syntaxhighlight lang="text">П1 <-> П0
+ С/П
+ С/П
ИП0 ИП1 - С/П
ИП0 ИП1 - С/П
Line 1,752: Line 3,589:
ИП0 ИП1 / [x] С/П
ИП0 ИП1 / [x] С/П
ИП0 ^ ИП1 / [x] ИП1 * - С/П
ИП0 ^ ИП1 / [x] ИП1 * - С/П
ИП1 ИП0 x^y С/П</lang>
ИП1 ИП0 x^y С/П</syntaxhighlight>


=={{header|ML/I}}==
=={{header|ML/I}}==
ML/I will read two integers from 'standard input' or similar, and then output the results to 'standard output' or similar.
ML/I will read two integers from 'standard input' or similar,
and then output the results to 'standard output' or similar.


<lang ML/I>MCSKIP "WITH" NL
<syntaxhighlight lang="ml/i">MCSKIP "WITH" NL
"" Arithmetic/Integer
"" Arithmetic/Integer
"" assumes macros on input stream 1, terminal on stream 2
"" assumes macros on input stream 1, terminal on stream 2
Line 1,771: Line 3,609:
Division is truncated to the greatest integer
Division is truncated to the greatest integer
that does not exceed the exact result. Remainder matches
that does not exceed the exact result. Remainder matches
the sign of the second operand, if the signs differ.</lang>
the sign of the second operand, if the signs differ.</syntaxhighlight>


=={{header|Modula-2}}==
=={{header|Modula-2}}==
<lang modula2>MODULE ints;
<syntaxhighlight lang="modula2">MODULE ints;


IMPORT InOut;
IMPORT InOut;
Line 1,790: Line 3,628:
InOut.WriteString ("a MOD b = "); InOut.WriteInt (a MOD b, 9); InOut.WriteLn;
InOut.WriteString ("a MOD b = "); InOut.WriteInt (a MOD b, 9); InOut.WriteLn;
InOut.WriteLn;
InOut.WriteLn;
END ints.</lang>Producing:<pre>$$ ints
END ints.</syntaxhighlight>Producing:<pre>$$ ints
Enter two integer numbers : 12 7
Enter two integer numbers : 12 7
a + b = 19
a + b = 19
Line 1,807: Line 3,645:


=={{header|Modula-3}}==
=={{header|Modula-3}}==
<lang modula3>MODULE Arith EXPORTS Main;
<syntaxhighlight lang="modula3">MODULE Arith EXPORTS Main;


IMPORT IO, Fmt;
IMPORT IO, Fmt;
Line 1,821: Line 3,659:
IO.Put("a DIV b = " & Fmt.Int(a DIV b) & "\n");
IO.Put("a DIV b = " & Fmt.Int(a DIV b) & "\n");
IO.Put("a MOD b = " & Fmt.Int(a MOD b) & "\n");
IO.Put("a MOD b = " & Fmt.Int(a MOD b) & "\n");
END Arith.</lang>
END Arith.</syntaxhighlight>


=={{header|MUMPS}}==
=={{header|MUMPS}}==
Line 1,832: Line 3,670:
find out the beauty of cyclic algebra as formulated by Niels Henrik Abel (August 5, 1802 – April 6, 1829).</p>
find out the beauty of cyclic algebra as formulated by Niels Henrik Abel (August 5, 1802 – April 6, 1829).</p>


<lang MUMPS>Arith(first,second) ; Mathematical operators
<syntaxhighlight lang="mumps">Arith(first,second) ; Mathematical operators
Write "Plus",?12,first,"+",second,?25," = ",first+second,!
Write "Plus",?12,first,"+",second,?25," = ",first+second,!
Write "Minus",?12,first,"-",second,?25," = ",first-second,!
Write "Minus",?12,first,"-",second,?25," = ",first-second,!
Line 1,875: Line 3,713:
Modulo 0#2 = 0
Modulo 0#2 = 0
And 0&2 = 0
And 0&2 = 0
Or 0!2 = 1</lang>
Or 0!2 = 1</syntaxhighlight>


=={{header|Nanoquery}}==
{{trans|Python}}
<syntaxhighlight lang="nanoquery">print "Number 1: "
x = int(input())
print "Number 2: "
y = int(input())

println format("Sum: %d", x + y)
println format("Difference: %d", x - y)
println format("Product: %d", x * y)
println format("Quotient: %f", x / y)

println format("Remainder: %d", x % y)
println format("Power: %d", x ^ y)</syntaxhighlight>

{{out}}
<pre>Number 1: 5
Number 2: 6
Sum: 11
Difference: -1
Product: 30
Quotient: 0.833333
Remainder: 5
Power: 15625</pre>


=={{header|Nemerle}}==
=={{header|Nemerle}}==
Adapted nearly verbatim from C# solution above. Note that I've used the exponentiation operator (**), but Math.Pow() as used in the C# solution would also work.
Adapted nearly verbatim from C# solution above. Note that I've used the exponentiation operator (**), but Math.Pow() as used in the C# solution would also work.
<lang Nemerle>using System;
<syntaxhighlight lang="nemerle">using System;
class Program
class Program
Line 1,896: Line 3,758:
Console.WriteLine("{0} ** {1} = {2}", a, b, a ** b);
Console.WriteLine("{0} ** {1} = {2}", a, b, a ** b);
}
}
}</lang>
}</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
{{trans|REXX}}
{{trans|REXX}}
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */


options replace format comments java crossref symbols binary
options replace format comments java crossref symbols binary
Line 1,913: Line 3,775:


return
return
</syntaxhighlight>
</lang>
{{out}}
;Output
<pre style="height: 15ex; overflow:scroll;">
<pre style="height: 15ex; overflow:scroll;">
enter 2 integer values separated by blanks
enter 2 integer values separated by blanks
Line 1,927: Line 3,789:
=={{header|NewLISP}}==
=={{header|NewLISP}}==


<lang NewLISP>; integer.lsp
<syntaxhighlight lang="newlisp">; integer.lsp
; oofoe 2012-01-17
; oofoe 2012-01-17


Line 1,951: Line 3,813:


(exit) ; NewLisp normally goes to listener after running script.
(exit) ; NewLisp normally goes to listener after running script.
</syntaxhighlight>
</lang>

Sample output:


{{out}}
<pre>
<pre>
Please type in an integer and press [enter]: 17
Please type in an integer and press [enter]: 17
Line 1,969: Line 3,830:
</pre>
</pre>


=={{header|Nim}}==
=={{header|Nial}}==
<lang nim>
import parseopt,strutils


Example tested with Q'Nial7.

Define new operator using an atlas of operators:
<syntaxhighlight lang="nial"> arithmetic is OP A B{[first,last,+,-,*,quotient,mod,power] A B}</syntaxhighlight>

Test new operator:
<syntaxhighlight lang="nial"> -23 arithmetic 7
-23 7 -16 -30 -161 -4 5 -3404825447</syntaxhighlight>

Negative divisors are not accepted for integer quotient <code>quotient</code> or remainder <code>mod</code>, and in both cases the result is an error with the message <code>?negative divisor</code>.

For <code>quotient</code>, if the divisor <code>B</code> is zero, the result is zero.

For <code>mod</code>, if the divisor <code>B</code> is zero, the result is <code>A</code>.

The quotient on division by a positive integer <code>B</code> is always an integer on the same side of the origin as <code>A</code>.

Nial definition of <code>quotient</code>:

<syntaxhighlight lang="nial">A quotient B =f= floor (A / B)</syntaxhighlight>

<code>floor</code> rounds towards negative infinity (next lower integer).

=={{header|Nim}}==
<syntaxhighlight lang="nim">import parseopt, strutils
var
var
opt: TOptParser = initOptParser()
opt: OptParser = initOptParser()
str = opt.cmdLineRest.split
str = opt.cmdLineRest.split
a: int = 0
a: int = 0
b: int = 0
b: int = 0

try:
try:
a = parseInt(str[0])
a = parseInt(str[0])
b = parseInt(str[1])
b = parseInt(str[1])
except EinvalidValue:
except ValueError:
quit("Invalid params. Two integers are expected.")
quit("Invalid params. Two integers are expected.")


echo ("a : " & $a)
echo("a : " & $a)
echo ("b : " & $b)
echo("b : " & $b)
echo ("a + b : " & $(a+b))
echo("a + b : " & $(a+b))
echo ("a - b : " & $(a-b))
echo("a - b : " & $(a-b))
echo ("a * b : " & $(a*b))
echo("a * b : " & $(a*b))
echo ("a div b: " & $(a div b))
echo("a div b: " & $(a div b)) # div rounds towards zero
echo ("a mod b: " & $(a mod b))
echo("a mod b: " & $(a mod b)) # sign(a mod b)==sign(a) if sign(a)!=sign(b)
echo("a ^ b : " & $(a ^ b))
</lang>
</syntaxhighlight>
Execute: Aritmint 10 23 <br>/
Execute: Aritmint 4 5
Output: <br/>
{{out}}
<pre>
<pre>
a : 10
a : 4
b : 23
b : 5
a + b : 33
a + b : 9
a - b : -13
a - b : -1
a * b : 230
a * b : 20
a div b: 0
a div b: 4
a mod b: 10
a mod b: 4
a ^ b : 1024
</pre>
</pre>


=={{header|NSIS}}==
=={{header|NSIS}}==
All Arithmetic in NSIS is handled by the [http://nsis.sourceforge.net/Docs/Chapter4.html#4.9.10.2 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.
All Arithmetic in NSIS is handled by the [http://nsis.sourceforge.net/Docs/Chapter4.html#4.9.10.2 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.
<lang nsis>Function Arithmetic
<syntaxhighlight lang="nsis">Function Arithmetic
Push $0
Push $0
Push $1
Push $1
Line 2,031: Line 3,918:
Pop $1
Pop $1
Pop $0
Pop $0
FunctionEnd</lang>
FunctionEnd</syntaxhighlight>

=={{header|Nu}}==
Division rounds towards -infinity. Modulus will match the sign of the first number.

<syntaxhighlight lang="nu">
input | parse "{a} {b}" | first | values | into int | do {|a b|
{
Sum: ($a + $b)
Difference: ($a - $b)
Product: ($a * $b)
Quotient: ($a // $b)
Remainder: ($a mod $b)
Exponent: ($a ** $b)
}
} $in.0 $in.1
</syntaxhighlight>
{{out}}
<pre>
-1 2
╭────────────┬────╮
│ Sum │ 1 │
│ Difference │ -3 │
│ Product │ -2 │
│ Quotient │ -1 │
│ Remainder │ -1 │
│ Exponent │ 1 │
╰────────────┴────╯
</pre>

=={{header|Nutt}}==
<syntaxhighlight lang="Nutt">
module main
imports native.io{input.hear,output.say}

vals a=hear(Numerable),b=hear(Numerable)
say("a+b="+(a+b))
say("a-b="+(a-b))
say("a*b="+(a*b))
say("a//b="+(a//b))
say("a%b="+(a%b))
say("a^b="+(a^b))

end
</syntaxhighlight>


=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
Oxford Oberon-2
Oxford Oberon-2
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE Arithmetic;
MODULE Arithmetic;
IMPORT In, Out;
IMPORT In, Out;
Line 2,048: Line 3,979:
Out.String("x MOD y >");Out.Int(x MOD y,6);Out.Ln;
Out.String("x MOD y >");Out.Int(x MOD y,6);Out.Ln;
END Arithmetic.
END Arithmetic.
</syntaxhighlight>
</lang>
{{out}}
Output:
<pre>
<pre>
Give two numbers: 12 23
Give two numbers: 12 23
Line 2,058: Line 3,989:
x MOD y > 12
x MOD y > 12
</pre>
</pre>

=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>bundle Default {
<syntaxhighlight lang="objeck">bundle Default {
class Arithmetic {
class Arithmetic {
function : Main(args : System.String[]) ~ Nil {
function : Main(args : System.String[]) ~ Nil {
Line 2,075: Line 4,007:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>let _ =
<syntaxhighlight lang="ocaml">let _ =
let a = read_int ()
let a = read_int ()
and b = read_int () in
and b = read_int () in
Line 2,086: Line 4,018:
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 / b = %d\n" (a / b); (* truncates towards 0 *)
Printf.printf "a mod b = %d\n" (a mod b) (* same sign as first operand *)</lang>
Printf.printf "a mod b = %d\n" (a mod b) (* same sign as first operand *)</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>: integers(b, a)
<syntaxhighlight lang="oforth">: integers (a b -- )
"a + b =" . a b + .cr
{
"a + b = " print a b + println
"a - b =" . a b - .cr
"a - b = " print a b - println
"a * b =" . a b * .cr
"a * b = " print a b * println
"a / b =" . a b / .cr
"a / b = " print a b / println
"a mod b =" . a b mod .cr
"a mod b = " print a b mod println
"a pow b =" . a b pow .cr
;</syntaxhighlight>
"a pow b = " print a b pow println
}</lang>


{{out}}
{{out}}
Line 2,110: Line 4,041:
a pow b = 6624737266949237011120128
a pow b = 6624737266949237011120128
ok
ok
</pre>

=={{header|Ol}}==

<syntaxhighlight lang="scheme">
(define a 8)
(define b 12)

(print "(+ " a " " b ") => " (+ a b))
(print "(- " a " " b ") => " (- a b))
(print "(* " a " " b ") => " (* a b))
(print "(/ " a " " b ") => " (/ a b))

(print "(quotient " a " " b ") => " (quot a b)) ; same as (quotient a b)
(print "(remainder " a " " b ") => " (rem a b)) ; same as (remainder a b)
(print "(modulo " a " " b ") => " (mod a b)) ; same as (modulo a b)

(print "(expt " a " " b ") => " (expt a b))
(print "(gcd " a " " b ") => " (gcd a b))
(print "(lcm " a " " b ") => " (lcm a b))

; you can use more than two arguments for +,-,*,/ functions
(print (+ 1 3 5 7 9))
(print (- 1 3 5 7 9))
(print (* 1 3 5 7 9)) ; same as (1*3*5*7*9)
(print (/ 1 3 5 7 9)) ; same as (((1/3)/5)/7)/9
</syntaxhighlight>
{{out}}
<pre>
(+ 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
(expt 8 12) => 68719476736
(gcd 8 12) => 4
(lcm 8 12) => 24
25
-23
945
1/945
</pre>

=={{header|Onyx}}==

<syntaxhighlight lang="onyx"># Most of this long script is mere presentation.
# All you really need to do is push two integers onto the stack
# and then execute add, sub, mul, idiv, or pow.

$ClearScreen { # Using ANSI terminal control
`\e[2J\e[1;1H' print flush
} bind def

$Say { # string Say -
`\n' cat print flush
} bind def

$ShowPreamble {
`To show how integer arithmetic in done in Onyx,' Say
`we\'ll use two numbers of your choice, which' Say
`we\'ll call A and B.\n' Say
} bind def

$Prompt { # stack: string --
stdout exch write pop flush
} def

$GetInt { # stack: name -- integer
dup cvs `Enter integer ' exch cat `: ' cat
Prompt stdin readline pop cvx eval def
} bind def

$Template { # arithmetic_operator_name label_string Template result_string
A cvs ` ' B cvs ` ' 5 ncat over cvs ` gives ' 3 ncat exch
A B dn cvx eval cvs `.' 3 ncat Say
} bind def

$ShowResults {
$add `Addition: ' Template
$sub `Subtraction: ' Template
$mul `Multiplication: ' Template
$idiv `Division: ' Template
`Note that the result of integer division is rounded toward zero.' Say
$pow `Exponentiation: ' Template
`Note that the result of raising to a negative power always gives a real number.' Say
} bind def

ClearScreen ShowPreamble $A GetInt $B GetInt ShowResults</syntaxhighlight>

{{out}}
<pre>
To show how integer arithmetic in done in Onyx,
we'll use two numbers of your choice, which
we'll call A and B.

Enter integer A: 34
Enter integer B: 2
Addition: 34 2 add gives 36.
Subtraction: 34 2 sub gives 32.
Multiplication: 34 2 mul gives 68.
Division: 34 2 idiv gives 17.
Note that the result of integer division is rounded toward zero.
Exponentiation: 34 2 pow gives 1156.
Note that the result of raising to a negative power always gives a real number.
</pre>
</pre>


=={{header|Openscad}}==
=={{header|Openscad}}==


<lang openscad>echo (a+b); /* Sum */
<syntaxhighlight lang="openscad">echo (a+b); /* Sum */
echo (a-b); /* Difference */
echo (a-b); /* Difference */
echo (a*b); /* Product */
echo (a*b); /* Product */
echo (a/b); /* Quotient */
echo (a/b); /* Quotient */
echo (a%b); /* Modulus */</lang>
echo (a%b); /* Modulus */</syntaxhighlight>


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>declare
<syntaxhighlight lang="oz">declare
StdIn = {New class $ from Open.file Open.text end init(name:stdin)}
StdIn = {New class $ from Open.file Open.text end init(name:stdin)}


Line 2,139: Line 4,176:
"A^B = "#{Pow A B}
"A^B = "#{Pow A B}
]
]
System.showInfo}</lang>
System.showInfo}</syntaxhighlight>

=={{header|Panda}}==
Use reflection to get all functions defined on numbers taking number and returning number.
<syntaxhighlight lang="panda">a=3 b=7 func:_bbf__number_number_number =>f.name.<b> '(' a b ')' ' => ' f(a b) nl</syntaxhighlight>

{{out}}
<pre>atan2 ( 3 7 ) => 0.40489178628508343
divide ( 3 7 ) => 0.42857142857142855
gt ( 3 7 ) => UNDEFINED!
gte ( 3 7 ) => UNDEFINED!
lt ( 3 7 ) => 3
lte ( 3 7 ) => 3
max ( 3 7 ) => 7
min ( 3 7 ) => 3
minus ( 3 7 ) => -4
mod ( 3 7 ) => 3
plus ( 3 7 ) => 10
pow ( 3 7 ) => 2187</pre>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
Integer division with <code>\</code> rounds to <math>-\infty</math>. There also exists the <code>\/</code> round-to-nearest (ties to <math>+\infty</math>) operator. Ordinary division <code>/</code> does not round but returns rationals if given integers with a non-integral quotient.
Integer division with <code>\</code> rounds to <math>-\infty</math>. There also exists the <code>\/</code> round-to-nearest (ties to <math>+\infty</math>) operator. Ordinary division <code>/</code> does not round but returns rationals if given integers with a non-integral quotient.
<lang parigp>arith(a,b)={
<syntaxhighlight lang="parigp">arith(a,b)={
print(a+b);
print(a+b);
print(a-b);
print(a-b);
Line 2,150: Line 4,205:
print(a%b);
print(a%b);
print(a^b);
print(a^b);
};</lang>
};</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
<lang pascal>program arithmetic(input, output)
<syntaxhighlight lang="pascal">program arithmetic(input, output)


var
var
Line 2,164: Line 4,219:
writeln('a*b = ', a*b);
writeln('a*b = ', a*b);
writeln('a/b = ', a div b, ', remainder ', a mod b);
writeln('a/b = ', a div b, ', remainder ', a mod b);
writeln('a^b = ',Power(a,b):4:2); {real power}
end.</lang>
writeln('a^b = ',IntPower(a,b):4:2); {integer power}
end.</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
{{works with|Perl|5.x}}
{{works with|Perl|5.x}}
<lang perl>my $a = <>;
<syntaxhighlight lang="perl">my $a = <>;
my $b = <>;
my $b = <>;


Line 2,178: Line 4,235:
"remainder: ", $a % $b, "\n",
"remainder: ", $a % $b, "\n",
"exponent: ", $a ** $b, "\n"
"exponent: ", $a ** $b, "\n"
;</lang>
;</syntaxhighlight>


=={{header|Perl 6}}==
=={{header|Phix}}==
{{libheader|Phix/pGUI}}
{{works with|Rakudo|#21 "Seattle"}}
{{libheader|Phix/online}}
<lang perl6>my Int $a = get.floor;
You can run this online [http://phix.x10.mx/p2js/ArithInt.htm here] (layout/space is not perfected yet).
my Int $b = get.floor;
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">lab</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">tab</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dlg</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">fmt</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
a = %d
b = %d
a + b = %d
a - b = %d
a * b = %d
a / b = %g (does not truncate)
remainder(a,b) = %d (same sign as first operand)
power(a,b) = %g
"""</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">valuechanged_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000000;">tab</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupGetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tab</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"VALUE"</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">scanf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d %d"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">+</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">-</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">*</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">/</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">),</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)})</span>
<span style="color: #7060A8;">IupSetStrAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupRefresh</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">lab</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Enter two numbers"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">tab</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupText</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"VALUECHANGED_CB"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"valuechanged_cb"</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"EXPAND=HORIZONTAL"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"(separated by a space)\n\n\n\n\n\n\n"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"EXPAND=BOTH"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">IupVbox</span><span style="color: #0000FF;">({</span><span style="color: #7060A8;">IupHbox</span><span style="color: #0000FF;">({</span><span style="color: #000000;">lab</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tab</span><span style="color: #0000FF;">},</span><span style="color: #008000;">"GAP=10,NORMALIZESIZE=VERTICAL"</span><span style="color: #0000FF;">),</span>
<span style="color: #7060A8;">IupHbox</span><span style="color: #0000FF;">({</span><span style="color: #000000;">res</span><span style="color: #0000FF;">})},</span><span style="color: #008000;">"MARGIN=5x5"</span><span style="color: #0000FF;">),</span>
<span style="color: #008000;">`SIZE=188x112,TITLE="Arithmetic/Integer"`</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
{{out}}
With an input of "2 3"
<pre>
a = 2
b = 3
a + b = 5
a - b = -1
a * b = 6
a / b = 0.666667 (does not truncate)
remainder(a,b) = 2 (same sign as first operand)
power(a,b) = 8
</pre>


=={{header|Phixmonti}}==
say 'sum: ', $a + $b;
<syntaxhighlight lang="phixmonti">def printOp
say 'difference: ', $a - $b;
swap print print nl
say 'product: ', $a * $b;
enddef
say 'integer quotient: ', $a div $b;

say 'remainder: ', $a % $b;
8 var a 3 var b
say 'exponentiation: ', $a**$b;</lang>
"a = " a printOp
"b = " b printOp


"a + b = " a b + printOp
Note that <code>div</code> doesn't always do integer division; it performs the operation "most appropriate to the
"a - b = " a b - printOp
operand types". [http://perlcabal.org/syn/S03.html#line_729 Synopsis 3] guarantees that <code>div</code> "on built-in integer types is equivalent to taking the floor of a real division". If you want integer division with other types, say <code>floor($a/$b)</code>.
"a * b = " a b * printOp
"int(a / b) = " a b / int printOp
"a mod b = " a b mod printOp
"a ^ b = " a b power printOp</syntaxhighlight>


=={{header|PHL}}==
=={{header|PHL}}==


<lang phl>module arith;
<syntaxhighlight lang="phl">module arith;


extern printf;
extern printf;
Line 2,215: Line 4,336:
return 0;
return 0;
]</lang>
]</syntaxhighlight>


=={{header|PHP}}==
=={{header|PHP}}==
<lang php><?php
<syntaxhighlight lang="php"><?php
$a = fgets(STDIN);
$a = fgets(STDIN);
$b = fgets(STDIN);
$b = fgets(STDIN);
Line 2,228: Line 4,349:
"truncating quotient: ", (int)($a / $b), "\n",
"truncating quotient: ", (int)($a / $b), "\n",
"flooring quotient: ", floor($a / $b), "\n",
"flooring quotient: ", floor($a / $b), "\n",
"remainder: ", $a % $b, "\n";
"remainder: ", $a % $b, "\n",
"power: ", $a ** $b, "\n"; // PHP 5.6+ only
?></lang>
?></syntaxhighlight>

=={{header|Picat}}==
<syntaxhighlight lang="picat">main =>
X = read_int(),
Y = read_int(),
foreach (Op in [+,-,*,div,rem])
R = apply(Op,X,Y),
printf("%d %w %d = %d\n", X, Op, Y, R)
end.
</syntaxhighlight>

{{out}}
<pre>
2 3
2 + 3 = 5
2 - 3 = -1
2 * 3 = 6
2 div 3 = 0
2 rem 3 = 2
</pre>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de math (A B)
<syntaxhighlight lang="picolisp">(de math (A B)
(prinl "Add " (+ A B))
(prinl "Add " (+ A B))
(prinl "Subtract " (- A B))
(prinl "Subtract " (- A B))
Line 2,239: Line 4,381:
(prinl "Div/rnd " (*/ A B)) # Rounds to next integer
(prinl "Div/rnd " (*/ A B)) # Rounds to next integer
(prinl "Modulus " (% A B)) # Sign of the first operand
(prinl "Modulus " (% A B)) # Sign of the first operand
(prinl "Power " (** A B)) )</lang>
(prinl "Power " (** A B)) )</syntaxhighlight>

=={{header|Piet}}==
=={{header|Piet}}==
[[File:PietArithmaticInteger.png]]<br>
[[File:PietArithmaticInteger.png]]<br>
Line 2,281: Line 4,424:


=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
get list (a, b);
get list (a, b);
put skip list (a+b);
put skip list (a+b);
Line 2,288: Line 4,431:
put skip list (trunc(a/b)); /* truncates towards zero. */
put skip list (trunc(a/b)); /* truncates towards zero. */
put skip list (mod(a, b)); /* Remainder is always positive. */
put skip list (mod(a, b)); /* Remainder is always positive. */
put skip list (rem(a, b)); /* Sign can be negative. */</lang>
put skip list (rem(a, b)); /* Sign can be negative. */</syntaxhighlight>

=={{header|Plain English}}==
<syntaxhighlight lang="plainenglish">To run:
Start up.
Demonstrate integer arithmetic.
Wait for the escape key.
Shut down.

To demonstrate integer arithmetic:
Write "Enter a number: " to the console without advancing.
Read a number from the console.
Write "Enter another number: " to the console without advancing.
Read another number from the console.
Show the arithmetic operations between the number and the other number.

To show the arithmetic operations between a number and another number:
Write the number plus the other number then " is the sum." to the console.
Write the number minus the other number then " is the difference." to the console.
Write the number times the other number then " is the product." to the console.
Show the division of the number by the other number.
Raise the number to the other number.
Write the number then " is the power." to the console.

To show the division of a number by another number:
Privatize the number.
Divide the number by the other number giving a quotient [rounding toward zero] and a remainder [with the same sign as the dividend].
Write the quotient then " is the quotient." to the console.
Write the remainder then " is the remainder." to the console.</syntaxhighlight>
{{out}}
<pre>
Enter a number: 44
Enter another number: 3
47 is the sum.
41 is the difference.
132 is the product.
14 is the quotient.
2 is the remainder.
85184 is the power.
</pre>


=={{header|Pop11}}==
=={{header|Pop11}}==


<lang pop11>;;; Setup token reader
<syntaxhighlight lang="pop11">;;; Setup token reader
vars itemrep;
vars itemrep;
incharitem(charin) -> itemrep;
incharitem(charin) -> itemrep;
Line 2,302: Line 4,484:
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 div b, 'a div b = %p\n');
printf(a mod b, 'a mod b = %p\n');</lang>
printf(a mod b, 'a mod b = %p\n');</syntaxhighlight>


=={{header|PostScript}}==
=={{header|PostScript}}==
<lang ps>/arithInteger {
<syntaxhighlight lang="ps">/arithInteger {
/x exch def
/x exch def
/y exch def
/y exch def
Line 2,314: Line 4,496:
x y mod =
x y mod =
x y exp =
x y exp =
} def</lang>
} def</syntaxhighlight>

=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang powershell>$a = [int] (Read-Host First Number)
<syntaxhighlight lang="powershell">$a = [int] (Read-Host First Number)
$b = [int] (Read-Host Second Number)
$b = [int] (Read-Host Second Number)


Line 2,324: Line 4,507:
Write-Host "Quotient: $($a / $b)"
Write-Host "Quotient: $($a / $b)"
Write-Host "Quotient, round to even: $([Math]::Round($a / $b))"
Write-Host "Quotient, round to even: $([Math]::Round($a / $b))"
Write-Host "Remainder, sign follows first: $($a % $b)"</lang>
Write-Host "Remainder, sign follows first: $($a % $b)"</syntaxhighlight>
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.
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.


Line 2,330: Line 4,513:


No exponentiation operator exists, but can be worked around with the .NET BCL:
No exponentiation operator exists, but can be worked around with the .NET BCL:
<lang powershell>[Math]::Pow($a, $b)</lang>
<syntaxhighlight lang="powershell">[Math]::Pow($a, $b)</syntaxhighlight>

=={{header|Processing}}==
<syntaxhighlight lang="processing">int a = 7, b = 5;

println(a + " + " + b + " = " + (a + b));
println(a + " - " + b + " = " + (a - b));
println(a + " * " + b + " = " + (a * b));
println(a + " / " + b + " = " + (a / b)); //Rounds towards zero
println(a + " % " + b + " = " + (a % b)); //Same sign as first operand</syntaxhighlight>
{{out}}
<pre>7 + 5 = 12
7 - 5 = 2
7 * 5 = 35
7 / 5 = 1
7 % 5 = 2</pre>

=={{header|ProDOS}}==
=={{header|ProDOS}}==
<lang ProDOS>IGNORELINE Note: This example includes the math module.
<syntaxhighlight lang="prodos">IGNORELINE Note: This example includes the math module.
include arithmeticmodule
include arithmeticmodule
:a
:a
Line 2,350: Line 4,549:
editvar /newvar /value=d /title=Do you want to calculate more numbers?
editvar /newvar /value=d /title=Do you want to calculate more numbers?
if -d- /hasvalue yes goto :a else goto :end
if -d- /hasvalue yes goto :a else goto :end
:end</lang>
:end</syntaxhighlight>


<lang ProDOS>IGNORELINE Note: This example does not use the math module.
<syntaxhighlight lang="prodos">IGNORELINE Note: This example does not use the math module.
:a
:a
editvar /newvar /value=a /title=Enter first integer:
editvar /newvar /value=a /title=Enter first integer:
Line 2,366: Line 4,565:
editvar /newvar /value=d /title=Do you want to calculate more numbers?
editvar /newvar /value=d /title=Do you want to calculate more numbers?
if -d- /hasvalue yes goto :a else goto :end
if -d- /hasvalue yes goto :a else goto :end
:end</lang>
:end</syntaxhighlight>


=={{header|Prolog}}==
=={{header|Prolog}}==
Line 2,374: Line 4,573:
Remainder (`rem`) matches the sign of its first operand.
Remainder (`rem`) matches the sign of its first operand.


<lang prolog>
<syntaxhighlight lang="prolog">


print_expression_and_result(M, N, Operator) :-
print_expression_and_result(M, N, Operator) :-
Line 2,386: Line 4,585:
maplist( print_expression_and_result(M, N), [+,-,*,//,rem,^] ).
maplist( print_expression_and_result(M, N), [+,-,*,//,rem,^] ).


</syntaxhighlight>
</lang>


Use thus:
Use thus:


<lang prolog>
<syntaxhighlight lang="prolog">
?- arithmetic_integer.
?- arithmetic_integer.
|: 5.
|: 5.
Line 2,401: Line 4,600:
5^7 is 78125
5^7 is 78125
true.
true.
</syntaxhighlight>
</lang>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang purebasic>OpenConsole()
<syntaxhighlight lang="purebasic">OpenConsole()
Define a, b
Define a, b
Line 2,420: Line 4,619:
Input()
Input()
CloseConsole()</lang>
CloseConsole()</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==


<lang python>x = int(raw_input("Number 1: "))
<syntaxhighlight lang="python">x = int(raw_input("Number 1: "))
y = int(raw_input("Number 2: "))
y = int(raw_input("Number 2: "))


Line 2,437: Line 4,636:


## Only used to keep the display up when the program ends
## Only used to keep the display up when the program ends
raw_input( )</lang>
raw_input( )</syntaxhighlight>


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:
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:


<lang python>def getnum(prompt):
<syntaxhighlight lang="python">def getnum(prompt):
while True: # retrying ...
while True: # retrying ...
try:
try:
Line 2,453: Line 4,652:
x = getnum("Number1: ")
x = getnum("Number1: ")
y = getnum("Number2: ")
y = getnum("Number2: ")
...</lang>
...</syntaxhighlight>


(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).
(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).
Line 2,462: Line 4,661:


=== Python 3.0 compatible code ===
=== Python 3.0 compatible code ===
<lang python>def arithmetic(x, y):
<syntaxhighlight lang="python">def arithmetic(x, y):
for op in "+ - * // % **".split():
for op in "+ - * // % **".split():
expr = "%(x)s %(op)s %(y)s" % vars()
expr = "%(x)s %(op)s %(y)s" % vars()
Line 2,469: Line 4,668:


arithmetic(12, 8)
arithmetic(12, 8)
arithmetic(input("Number 1: "), input("Number 2: "))</lang>
arithmetic(input("Number 1: "), input("Number 2: "))</syntaxhighlight>
{{out}}
Output:
<pre>12 + 8 => 20
<pre>12 + 8 => 20
12 - 8 => 4
12 - 8 => 4
Line 2,485: Line 4,684:
20 % 4 => 0
20 % 4 => 0
20 ** 4 => 160000</pre>
20 ** 4 => 160000</pre>

== Python 3.x Long Form ==
<syntaxhighlight lang="python">input1 = 18
# input1 = input()
input2 = 7
# input2 = input()

qq = input1 + input2
print("Sum: " + str(qq))
ww = input1 - input2
print("Difference: " + str(ww))
ee = input1 * input2
print("Product: " + str(ee))
rr = input1 / input2
print("Integer quotient: " + str(int(rr)))
print("Float quotient: " + str(float(rr)))
tt = float(input1 / input2)
uu = (int(tt) - float(tt))*-10
#print(tt)
print("Whole Remainder: " + str(int(uu)))
print("Actual Remainder: " + str(uu))
yy = input1 ** input2
print("Exponentiation: " + str(yy))</syntaxhighlight>

{{Out}}
<pre>Sum: 25
Difference: 11
Product: 126
Integer quotient: 2
Float quotient: 2.5714285714285716
Whole Remainder: 5
Actual Remainder: 5.714285714285716
Exponentiation: 612220032</pre>

=={{header|QB64}}==
''CBTJD'': 2020/03/12
<syntaxhighlight lang="vb">START:
INPUT "Enter two integers (a,b):"; a!, b!
IF a = 0 THEN END
IF b = 0 THEN
PRINT "Second integer is zero. Zero not allowed for Quotient or Remainder."
GOTO START
END IF
PRINT
PRINT " Sum = "; a + b
PRINT " Difference = "; a - b
PRINT " Product = "; a * b
' Notice the use of the INTEGER Divisor "\" as opposed to the regular divisor "/".
PRINT "Integer Quotient = "; a \ b, , "* Rounds toward 0."
PRINT " Remainder = "; a MOD b, , "* Sign matches first operand."
PRINT " Exponentiation = "; a ^ b
PRINT
INPUT "Again? (y/N)"; a$
IF UCASE$(a$) = "Y" THEN CLS: GOTO START
CLS
END</syntaxhighlight>

=={{header|Quackery}}==

<syntaxhighlight lang="quackery "> $ "Please enter two integers separated by a space. "
input quackery
2dup say "Their sum is: " + echo cr
2dup say "Their difference is: " - echo cr
2dup say "Their product is: " " * echo cr
2dup say "Their integer quotient is: " / echo cr
2dup say "Their remainder is: " mod echo cr
say "Their exponentiation is: " ** echo cr
cr
say "Quotient rounds towards negative infinity." cr
say "Remainder matches the sign of the second argument."</syntaxhighlight>

{{Out}}

<pre>Please enter two integers separated by a space. 543 21
Their sum is: 564
Their difference is: 522
Their product is: 11403
Their integer quotient is: 25
Their remainder is: 18
Their exponentiation is: 2696475144200627485897267767746883957141292127831428752543
</pre>


=={{header|R}}==
=={{header|R}}==
<lang R>cat("insert number ")
<syntaxhighlight lang="r">cat("insert number ")
a <- scan(nmax=1, quiet=TRUE)
a <- scan(nmax=1, quiet=TRUE)
cat("insert number ")
cat("insert number ")
Line 2,497: Line 4,777:
print(paste('a%%b=', a%%b))
print(paste('a%%b=', a%%b))
print(paste('a^b=', a^b))
print(paste('a^b=', a^b))
</syntaxhighlight>
</lang>


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket/base

(define (arithmetic x y)
(define (arithmetic x y)
(for ([op '(+ - * / quotient remainder modulo max min gcd lcm)])
(for ([op (list + - * / quotient remainder modulo max min gcd lcm)])
(displayln (~a (list op x y) " => "
(printf "~s => ~s\n" `(,(object-name op) ,x ,y) (op x y))))

((eval op (make-base-namespace)) x y)))))
(arithmetic 8 12)
(arithmetic 8 12)
</syntaxhighlight>
</lang>
{{out}}
Output:
<pre>
<pre>
(+ 8 12) => 20
(+ 8 12) => 20
Line 2,523: Line 4,803:
(lcm 8 12) => 24
(lcm 8 12) => 24
</pre>
</pre>

=={{header|Raku}}==
(formerly Perl 6)

Note that <code>div</code> <b>requires</b> integer arguments. If you want integer division with other types, say <code>floor($a/$b)</code>.
<syntaxhighlight lang="raku" line>my Int $a = get.floor;
my Int $b = get.floor;

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;</syntaxhighlight>

=={{header|Raven}}==
=={{header|Raven}}==


<lang raven>' Number 1: ' print expect 0 prefer as x
<syntaxhighlight lang="raven">' Number 1: ' print expect 0 prefer as x
' Number 2: ' print expect 0 prefer as y
' Number 2: ' print expect 0 prefer as y


Line 2,532: Line 4,827:
x y * " product: %d\n" print
x y * " product: %d\n" print
x y / " quotient: %d\n" print
x y / " quotient: %d\n" print
x y % " remainder: %d\n" print</lang>
x y % " remainder: %d\n" print</syntaxhighlight>


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang rebol>REBOL [
<syntaxhighlight lang="rebol">REBOL [
Title: "Integer"
Title: "Integer"
Author: oofoe
Date: 2010-09-29
URL: http://rosettacode.org/wiki/Arithmetic/Integer
URL: http://rosettacode.org/wiki/Arithmetic/Integer
]
]
Line 2,587: Line 4,880:
]
]


print ["Exponentiation:" x ** y]</lang>
print ["Exponentiation:" x ** y]</syntaxhighlight>

Sample output:


{{out}}
<pre>Please type in an integer, and press [enter]: 17
<pre>Please type in an integer, and press [enter]: 17
Please enter another integer: -4
Please enter another integer: -4
Line 2,607: Line 4,899:
Remainder sign matches: first
Remainder sign matches: first
Exponentiation: 1.19730367213036E-5</pre>
Exponentiation: 1.19730367213036E-5</pre>

=={{header|Relation}}==
There is no input, variables have to be set in code. Format is there only for output.
<syntaxhighlight lang="relation">
set a = -17
set b = 4
echo "a+b = ".format(a+b,"%1d")
echo "a-b = ".format(a-b,"%1d")
echo "a*b = ".format(a*b,"%1d")
echo "a DIV b = ".format(floor(a/b),"%1d")
echo "a MOD b = ".format(a mod b,"%1d")
echo "a^b = ".format(pow(a,b),"%1d")
</syntaxhighlight>

=={{header|ReScript}}==

<syntaxhighlight lang="rescript">let a = int_of_string(Sys.argv[2])
let b = int_of_string(Sys.argv[3])

let sum = a + b
let difference = a - b
let product = a * b
let division = a / b
let remainder = mod(a, b)

Js.log("a + b = " ++ string_of_int(sum))
Js.log("a - b = " ++ string_of_int(difference))
Js.log("a * b = " ++ string_of_int(product))
Js.log("a / b = " ++ string_of_int(division))
Js.log("a % b = " ++ string_of_int(remainder))</syntaxhighlight>

{{out}}

<pre>$ bsc arith.res > arith.bs.js
$ node arith.bs.js 10 7
a + b = 17
a - b = 3
a * b = 70
a / b = 1
a % b = 3
</pre>


=={{header|Retro}}==
=={{header|Retro}}==
Retro's arithmetic functions are based on those in [[Forth]]. The example is an adaption of the one from Forth.
Retro's arithmetic functions are based on those in [[Forth]]. The example is an adaption of the one from Forth.
<lang Retro>: arithmetic ( ab- )
<syntaxhighlight lang="retro">:arithmetic (ab-)
over "\na = %d" puts
over '\na_______=_%n s:put
dup "\nb = %d" puts
dup '\nb_______=_%n s:put
2over + "\na + b = %d" puts
dup-pair + '\na_+_b___=_%n s:put
2over - "\na - b = %d" puts
dup-pair - '\na_-_b___=_%n s:put
2over * "\na * b = %d" puts
dup-pair * '\na_*_b___=_%n s:put
/mod "\na / b = %d" puts
/mod '\na_/_b___=_%n s:put
"\na mod b = %d\n" puts ;</lang>
'\na_mod_b_=_%n\n" s:put ;</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
All operators automatically produce integers where appropriate &nbsp; (up to twenty decimal digits in the program below),
<lang rexx>/*REXX pgm gets 2 integers from the C,L. or via prompt; shows some operations.*/
<br>or numbers in exponential format when necessary. &nbsp; (The REXX default is &nbsp; '''9''' &nbsp; decimal digits.)
numeric digits 20 /*#s are round at 20th significant dig.*/

parse arg x y . /*maybe the integers are on the C.L. */
For division that produces a floating point number, the result is rounded to the nearest number that can be expressed
<br>within the current number of decimal digits &nbsp; (in the example program below, it is &nbsp; '''20''' &nbsp; decimal digits).
<syntaxhighlight lang="rexx">/*REXX program obtains two integers from the C.L. (a prompt); displays some operations.*/
numeric digits 20 /*#s are round at 20th significant dig.*/
parse arg x y . /*maybe the integers are on the C.L. */


do while \datatype(x,'W') | \datatype(y,'W') /*both X and Y must be ints.*/
do while \datatype(x,'W') | \datatype(y,'W') /*both X and Y must be integers. */
say "─────Enter two integer values (separated by blanks):"
say "─────Enter two integer values (separated by blanks):"
parse pull x y . /*accept two items from command line. */
parse pull x y . /*accept two thingys from command line.*/
end /*while ··· */
end /*while*/
/* [↓] perform this DO loop twice. */
/* [↓] perform this DO loop twice. */
do j=1 for 2 /*show A oper B, then B oper A.*/
do j=1 for 2 /*show A oper B, then B oper A.*/
call show 'addition' , "+", x+y
call show 'addition' , "+", x+y
call show 'subtraction' , "-", x-y
call show 'subtraction' , "-", x-y
Line 2,639: Line 4,977:
call show 'power' , "**", x**y
call show 'power' , "**", x**y


parse value x y with y x /*swap the two values and perform again*/
parse value x y with y x /*swap the two values and perform again*/
if j==1 then say copies('═', 79) /*display a fence after the 1st round. */
if j==1 then say copies('═', 79) /*display a fence after the 1st round. */
end /*j*/
end /*j*/
exit /*stick a fork in it, we're all done. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*────────────────────────────────────────────────────────────────────────────*/
show: parse arg c,o,#,?; say right(c,25)' ' x center(o,4) y ' ───► ' # ?; return</lang>
show: parse arg c,o,#,?; say right(c,25)' ' x center(o,4) y " ───► " # ?; return</syntaxhighlight>
'''output''' when using the input of: &nbsp; <tt> 17 &nbsp; -4 </tt>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 4 &nbsp; -17 </tt>}}
<pre>
<pre>
addition 4 + -17 ───► -13
addition 4 + -17 ───► -13
Line 2,662: Line 5,000:
division remainder -17 // 4 ───► -1 [sign from 1st operand]
division remainder -17 // 4 ───► -1 [sign from 1st operand]
power -17 ** 4 ───► 83521
power -17 ** 4 ───► 83521
</pre>

=={{header|Ring}}==
<syntaxhighlight lang="ring">
func Test a,b
see "a+b" + ( a + b ) + nl
see "a-b" + ( a - b ) + nl
see "a*b" + ( a * b ) + nl
// The quotient isn't integer, so we use the Ceil() function, which truncates it downward.
see "a/b" + Ceil( a / b ) + nl
// Remainder:
see "a%b" + ( a % b ) + nl
see "a**b" + pow(a,b ) + nl
</syntaxhighlight>

=={{header|Robotic}}==
<syntaxhighlight lang="robotic">
input string "Enter number 1:"
set "a" to "input"
input string "Enter number 2:"
set "b" to "input"

[ "Sum: ('a' + 'b')"
[ "Difference: ('a' - 'b')"
[ "Product: ('a' * 'b')"
[ "Integer Quotient: ('a' / 'b')"
[ "Remainder: ('a' % 'b')"
[ "Exponentiation: ('a'^'b')"
</syntaxhighlight>

=={{header|RPL}}==
≪ → a b
≪ "a + b = " a b + →STR +
"a - b = " a b - →STR +
"a * b = " a b * →STR +
"a / b = " a b / →STR +
"a % b = " a b / LAST ROT * - →STR +
"a ^ b = " a B→R b B→R ^ R→B →STR +
≫ ≫ '<span style="color:blue">SHOWA</span>' STO

#14 #3 <span style="color:blue">SHOWA</span>
<pre>
6: "a + b = # 17d"
5: "a - b = # 11d"
4: "a * b = # 42d"
3: "a / b = # 4d"
2: "a % b = # 2d"
1: "a ^ b = # 2744d"
</pre>
</pre>


=={{header|Ruby}}==
=={{header|Ruby}}==


<lang ruby>puts 'Enter x and y'
<syntaxhighlight lang="ruby">puts 'Enter x and y'
x = gets.to_i # to check errors, use x=Integer(gets)
x = gets.to_i # to check errors, use x=Integer(gets)
y = gets.to_i
y = gets.to_i
Line 2,676: Line 5,062:
"Quotient: #{x.fdiv(y)}", # float
"Quotient: #{x.fdiv(y)}", # float
"Remainder: #{x%y}", # same sign as second operand
"Remainder: #{x%y}", # same sign as second operand
"Exponentiation: #{x**y}"</lang>
"Exponentiation: #{x**y}",
"Quotient: %d with Remainder: %d" % x.divmod(y)</syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>input "1st integer: "; i1
<syntaxhighlight lang="runbasic">input "1st integer: "; i1
input "2nd integer: "; i2
input "2nd integer: "; i2
Line 2,687: Line 5,074:
if i2 <>0 then print " Quotent "; int( i1 / i2); else print "Cannot divide by zero."
if i2 <>0 then print " Quotent "; int( i1 / i2); else print "Cannot divide by zero."
print "Remainder"; i1 MOD i2
print "Remainder"; i1 MOD i2
print "1st raised to power of 2nd"; i1 ^ i2</lang>
print "1st raised to power of 2nd"; i1 ^ i2</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==


Note that this code cannot be run within the [http://play.rust-lang.org Rust playpen] as it does not support console input.
Note that this code cannot be run within the [http://play.rust-lang.org Rust playpen] as it does not support console input.
<lang rust>use std::io;
<syntaxhighlight lang="rust">use std::env;


fn main() {
fn main() {
let args: Vec<_> = env::args().collect();
#![allow(unstable)] // Currently required whilst Rust 1.0 is finalised
let a: i32 = from_str(io::stdin().read_line().unwrap().trim().as_slice()).unwrap();
let a = args[1].parse::<i32>().unwrap();
let b: i32 = from_str(io::stdin().read_line().unwrap().trim().as_slice()).unwrap();
let b = args[2].parse::<i32>().unwrap();


let sum = a + b;
println!("sum: {}", a + b);
println!("a + b = {0}" , sum);
println!("difference: {}", a - b);
println!("a - b = {0}" , a - b);
println!("product: {}", a * b);
println!("a * b = {0}" , a * b);
println!("integer quotient: {}", a / b); // truncates towards zero
println!("quotient of a / b = {0}" , a / b); // truncates towards 0
println!("remainder: {}", a % b); // same sign as first operand
}</syntaxhighlight>
println!("remainder of a / b = {0}" , a % b); // same sign as first operand
}</lang>


=={{header|Sass/SCSS}}==
=={{header|Sass/SCSS}}==


<lang coffeescript>
<syntaxhighlight lang="coffeescript">
@function arithmetic($a,$b) {
@function arithmetic($a,$b) {
@return $a + $b, $a - $b, $a * $b, ($a - ($a % $b))/$b, $a % $b;
@return $a + $b, $a - $b, $a * $b, ($a - ($a % $b))/$b, $a % $b;
}
}
</syntaxhighlight>
</lang>
Which you use with:
Which you use with:
<lang coffeescript>
<syntaxhighlight lang="coffeescript">
nth(arithmetic(10,3),1);
nth(arithmetic(10,3),1);
</syntaxhighlight>
</lang>
Or each of the functions separately:
Or each of the functions separately:
<lang coffeescript>
<syntaxhighlight lang="coffeescript">
@function sum($a,$b) {
@function sum($a,$b) {
@return $a + $b;
@return $a + $b;
Line 2,743: Line 5,129:
@return $a / $b;
@return $a / $b;
}
}
</syntaxhighlight>
</lang>


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>val a = Console.readInt
<syntaxhighlight lang="scala">val a = Console.readInt
val b = Console.readInt
val b = Console.readInt
Line 2,754: Line 5,140:
println("a * b = " + (a * b))
println("a * b = " + (a * b))
println("quotient of a / b = " + (a / b)) // truncates towards 0
println("quotient of a / b = " + (a / b)) // truncates towards 0
println("remainder of a / b = " + (a % b)) // same sign as first operand</lang>
println("remainder of a / b = " + (a % b)) // same sign as first operand</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==


<lang scheme>(define (arithmetic x y)
<syntaxhighlight lang="scheme">(define (arithmetic x y)
(for-each (lambda (op)
(for-each (lambda (op)
(write (list op x y))
(write (list op x y))
Line 2,766: Line 5,152:
'(+ - * / quotient remainder modulo max min gcd lcm)))
'(+ - * / quotient remainder modulo max min gcd lcm)))
(arithmetic 8 12)</lang>
(arithmetic 8 12)</syntaxhighlight>
quotient - truncates towards 0
quotient - truncates towards 0
remainder - same sign as first operand
remainder - same sign as first operand
Line 2,786: Line 5,172:


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";


const proc: main is func
const proc: main is func
Line 2,805: Line 5,191:
writeln("a mdiv b = " <& a mdiv b); # Rounds towards negative infinity
writeln("a mdiv b = " <& a mdiv b); # Rounds towards negative infinity
writeln("a mod b = " <& a mod b); # Sign of the second operand
writeln("a mod b = " <& a mod b); # Sign of the second operand
end func;</lang>
end func;</syntaxhighlight>

=={{header|SenseTalk}}==
<syntaxhighlight lang="sensetalk">ask "Enter the first number:"
put it into number1

ask "Enter the second number:"
put it into number2

put "Sum: " & number1 plus number2
put "Difference: " & number1 minus number2
put "Product: " & number1 multiplied by number2
put "Integer quotient: " & number1 div number2 -- Rounding towards 0
put "Remainder: " & number1 rem number2
put "Exponentiation: " & number1 to the power of number2</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>var a = Sys.scanln("First number: ").to_i;
<syntaxhighlight lang="ruby">var a = Sys.scanln("First number: ").to_i;
var b = Sys.scanln("Second number: ").to_i;
var b = Sys.scanln("Second number: ").to_i;


%w'+ - * / % ** ^ | & << >>'.each { |op|
%w'+ - * // % ** ^ | & << >>'.each { |op|
"#{a} #{op} #{b} = #{a.$op(b)}".say;
"#{a} #{op} #{b} = #{a.$op(b)}".say;
}</lang>
}</syntaxhighlight>


{{out}}
'''Output:'''
<pre>
<pre>
First number: 1234
** Integer a: 100
Second number: 7
** Integer b: 20
100 + 20 = 120
1234 + 7 = 1241
100 - 20 = 80
1234 - 7 = 1227
100 * 20 = 2000
1234 * 7 = 8638
100 / 20 = 5
1234 // 7 = 176
100 % 20 = 0
1234 % 7 = 2
1234 ** 7 = 4357186184021382204544
100 ** 20 = 10000000000000000000000000000000000000000
100 ^ 20 = 112
1234 ^ 7 = 1237
100 | 20 = 116
1234 | 7 = 1239
100 & 20 = 4
1234 & 7 = 2
100 << 20 = 104857600
1234 << 7 = 157952
100 >> 20 = 0
1234 >> 7 = 9
</pre>
</pre>


=={{header|Slate}}==
=={{header|Slate}}==
<lang slate>[| :a :b |
<syntaxhighlight lang="slate">[| :a :b |
inform: (a + b) printString.
inform: (a + b) printString.
inform: (a - b) printString.
inform: (a - b) printString.
Line 2,841: Line 5,241:
inform: (a \\ b) printString.
inform: (a \\ b) printString.


] applyTo: {Integer readFrom: (query: 'Enter a: '). Integer readFrom: (query: 'Enter b: ')}.</lang>
] applyTo: {Integer readFrom: (query: 'Enter a: '). Integer readFrom: (query: 'Enter b: ')}.</syntaxhighlight>

=={{header|SmallBASIC}}==
<syntaxhighlight lang="SmallBASIC">
input "Enter first number : "; A
input "Enter second number: "; B

print "Sum : "; A + B
print "Difference: "; A - B
print "Product : "; A * B
print "Quotient : "; A \ B ' Integer quotient rounds towards smaller number
print "Remainder : "; A % B ' sign of remainder is given by sign of first operand
print "Power : "; A ^ B
</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
{{works with|GNU Smalltalk}}
<lang smalltalk>| a b |
<syntaxhighlight lang="smalltalk">| a b |
'Input number a: ' display.
'Input number a: ' display.
a := (stdin nextLine) asInteger.
a := (stdin nextLine) asInteger.
Line 2,854: Line 5,267:
('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.</lang>
('a%%b=%1' % { a \\ b }) displayNl.</syntaxhighlight>

{{works with|Smalltalk/X}} (and all other Smalltalks)
<syntaxhighlight lang="smalltalk">|a b|
a := (Dialog request:'Enter first number:') asNumber.
b := (Dialog request:'Enter second number:') asNumber.
#( + - / * // \\ quo: rem: raisedTo: **) do:[:operator |
|result|
result := a perform:operator with:b.
'%P %s %P => %P\n' printf:{a . operator . b . result} on:Transcript
].</syntaxhighlight>
/ is exact division
<br>// is truncating division (towards negative infinity)
<br>\\ is remainder from \\
<br>quo: is truncating division (towards zero)
<br>\\ is remainder from quo:
<br>** is just an alias for raisedTo:
<p>Entering 10 and 3, generates:
{{out}}
<pre>
10 + 3 => 13
10 - 3 => 7
10 / 3 => (10/3)
10 * 3 => 30
10 // 3 => 3
10 \\ 3 => 1
10 quo: 3 => 3
10 rem: 3 => 1
10 raisedTo: 3 => 1000
10 ** 3 => 1000
</pre>
Entering 10 and -3 generates:
{{out}}
<pre>
10 + -3 => 7
10 - -3 => 13
10 / -3 => (-10/3)
10 * -3 => -30
10 // -3 => -4
10 \\ -3 => -2
10 quo: -3 => -3
10 rem: -3 => 1
10 raisedTo: -3 => (1/1000)
10 ** -3 => (1/1000)
</pre>
Entering 20 and 50 generates (notice the fraction and the long integer results):
{{out}}
<pre>
20 + 50 => 70
20 - 50 => -30
20 / 50 => (2/5)
20 * 50 => 1000
20 // 50 => 0
20 \\ 50 => 20
20 quo: 50 => 0
20 rem: 50 => 20
20 raisedTo: 50 => 112589990684262400000000000000000000000000000000000000000000000000
20 ** 50 => 112589990684262400000000000000000000000000000000000000000000000000
</pre>

=={{header|smart BASIC}}==
<syntaxhighlight lang="qbasic">INPUT "Enter first number.":first
INPUT "Enter second number.":second
PRINT "The sum of";first;"and";second;"is ";first+second&"."
PRINT "The difference between";first;"and";second;"is ";ABS(first-second)&"."
PRINT "The product of";first;"and";second;"is ";first*second&"."
IF second THEN
PRINT "The integer quotient of";first;"and";second;"is ";INTEG(first/second)&"."
ELSE
PRINT "Division by zero not cool."
ENDIF
PRINT "The remainder being...";first%second&"."
PRINT STR$(first);"raised to the power of";second;"is ";first^second&"."</syntaxhighlight>

'''NOTES:''' Some curious aspects of smart BASIC to note in this code example:
<ol>
<li>In smart BASIC, The command INTEG is a true integer function providing only the value of the characteristic. The smart BASIC INT command calculates as a rounding function. This differs from some other versions of BASIC.</li>
<li>smart BASIC automatically inserts spaces ahead of and behind numbers. This can cause unexpected formatting issues when combining output from numeric variables with text. In order to suppress the trailing space, you must use the ampersand (&) to concatenate the numeric value with the following text (in this case, a period at the end of each sentence). In the case of leading spaces, you must convert the numeric value to text using the STR$ command (as with the last line of the code).
</ol>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
<lang snobol4>
<syntaxhighlight lang="snobol4">
output = "Enter first integer:"
output = "Enter first integer:"
first = input
first = input
Line 2,867: Line 5,358:
output = "quot = " (qout = first / second)
output = "quot = " (qout = first / second)
output = "rem = " first - (qout * second)
output = "rem = " first - (qout * second)
output = "expo = " first ** second
end</lang>
end</syntaxhighlight>


=={{header|SNUSP}}==
=={{header|SNUSP}}==
Line 2,873: Line 5,365:


''See also: [[Ethiopian Multiplication]]''
''See also: [[Ethiopian Multiplication]]''
<syntaxhighlight lang="snusp">$\
<lang SNUSP>$\
,
,
@
@
Line 2,930: Line 5,422:
\=@@@+@+++++#
\=@@@+@+++++#
.
.
#</lang>
#</syntaxhighlight>

=={{header|SQL}}==
{{works with|Oracle}}
<syntaxhighlight lang="sql">
-- test.sql
-- Tested in SQL*plus

drop table test;

create table test (a integer, b integer);

insert into test values ('&&A','&&B');

commit;

select a-b difference from test;

select a*b product from test;

select trunc(a/b) integer_quotient from test;

select mod(a,b) remainder from test;

select power(a,b) exponentiation from test;
</syntaxhighlight>

<pre>
SQL> @test.sql

Table dropped.


Table created.

Enter value for a: 3
Enter value for b: 4
old 1: insert into test values ('&&A','&&B')
new 1: insert into test values ('3','4')

1 row created.


Commit complete.


DIFFERENCE
----------
-1


PRODUCT
----------
12


INTEGER_QUOTIENT
----------------
0


REMAINDER
----------
3


EXPONENTIATION
--------------
81
</pre>

=={{header|SSEM}}==
The only operation that the SSEM supports natively is substraction. This program uses the <tt>001 Sub.</tt> instruction to find the difference between <i>a</i> and <i>b</i>, assuming they are loaded into storage addresses 20 and 21 respectively.
<syntaxhighlight lang="ssem">00101000000000100000000000000000 0. -20 to c
10100000000001100000000000000000 1. c to 5
10100000000000100000000000000000 2. -5 to c
10101000000000010000000000000000 3. Sub. 21
00000000000001110000000000000000 4. Stop
00000000000000000000000000000000 5. 0</syntaxhighlight>
The routine is slightly more complicated than it would otherwise be, because the SSEM cannot load a value into the accumulator (<tt>c</tt> register) from storage without negating it in the process—so we have to shuffle the negation of <i>a</i> back out into storage and then negate it again before we can subtract <i>b</i> from it. This does, however, make it easy to implement addition using negation and subtraction. In this program, we first negate <i>a</i>; then subtract <i>b</i>, and store the result; and finally negate that result, thereby obtaining the sum of the two integers.
<syntaxhighlight lang="ssem">00101000000000100000000000000000 0. -20 to c
10101000000000010000000000000000 1. Sub. 21
10100000000001100000000000000000 2. c to 5
10100000000000100000000000000000 3. -5 to c
00000000000001110000000000000000 4. Stop
00000000000000000000000000000000 5. 0</syntaxhighlight>
A multiplication program will be found at [[Function definition#SSEM]], and one that performs integer division at [[Loops/For with a specified step#SSEM]].


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>val () = let
<syntaxhighlight lang="sml">val () = let
val a = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn)))
val a = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn)))
val b = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn)))
val b = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn)))
Line 2,945: Line 5,524:
print ("a rem b = " ^ Int.toString (Int.rem (a, b)) ^ "\n"); (* same sign as first operand *)
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 *)
print ("~a = " ^ Int.toString (~a) ^ "\n") (* unary negation, unusual notation compared to other languages *)
end</lang>
end</syntaxhighlight>

=={{header|Swift}}==
<syntaxhighlight lang="swift">
let a = 6
let b = 4

print("sum =\(a+b)")
print("difference = \(a-b)")
print("product = \(a*b)")
print("Integer quotient = \(a/b)")
print("Remainder = (a%b)")
print("No operator for Exponential")
</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>puts "Please enter two numbers:"
<syntaxhighlight lang="tcl">puts "Please enter two numbers:"


set x [expr {int([gets stdin])}]; # Force integer interpretation
set x [expr {int([gets stdin])}]; # Force integer interpretation
Line 2,958: Line 5,550:
puts "$x / $y = [expr {$x / $y}]"
puts "$x / $y = [expr {$x / $y}]"
puts "$x mod $y = [expr {$x % $y}]"
puts "$x mod $y = [expr {$x % $y}]"
puts "$x 'to the' $y = [expr {$x ** $y}]"</lang>
puts "$x 'to the' $y = [expr {$x ** $y}]"</syntaxhighlight>


Since Tcl doesn't really know about the "type" of a variable, the "<tt>expr</tt>" 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 <tt>int([gets&nbsp;stdin])</tt>.
Since Tcl doesn't really know about the "type" of a variable, the "<tt>expr</tt>" 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 <tt>int([gets&nbsp;stdin])</tt>.
Line 2,964: Line 5,556:
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
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


<lang tcl>incr x $y</lang>
<syntaxhighlight lang="tcl">incr x $y</syntaxhighlight>


Also, it's important to surround the arguments to the <code>expr</code> in braces, especially when any of the parts of the expression are not literal constants. Discussion of this is on [http://wiki.tcl.tk/10225 The Tcler's Wiki].
Also, it's important to surround the arguments to the <code>expr</code> in braces, especially when any of the parts of the expression are not literal constants. Discussion of this is on [http://wiki.tcl.tk/10225 The Tcler's Wiki].

=={{header|Terraform}}==
HCL doesn't have an exponentiation operator and even integer division is contrived as shown in the code, but at least it prints the output variables alphabetically without any effort.......
<syntaxhighlight lang="terraform">
#Aamrun, 15th August 2022

variable "a" {
type = number
}

variable "b" {
type = number
}

output "Sum" {
value = var.a + var.b
}

output "Difference" {
value = var.a - var.b
}

output "Product" {
value = var.a * var.b
}

output "Quotient" {
value = floor(var.a / var.b)
}

output "Remainder" {
value = var.a % var.b
}
</syntaxhighlight>
The floor function rounds to the closest lowest integer. Invocation and output are as below :
{{out}}
<pre>
$ terraform apply -var="a=19" -var="b=7" -auto-approve

Changes to Outputs:
+ Difference = 12
+ Product = 133
+ Quotient = 2
+ Remainder = 5
+ Sum = 26

You can apply this plan to save these new output values to the Terraform state, without changing any real infrastructure.

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

Difference = 12
Product = 133
Quotient = 2
Remainder = 5
Sum = 26
$
</pre>


=={{header|TI-83 BASIC}}==
=={{header|TI-83 BASIC}}==
Pauses added due to TI-83's lack of screen size.
Pauses added due to TI-83's lack of screen size.
<lang ti83b>
<syntaxhighlight lang="ti83b">
Prompt A,B
Prompt A,B
Disp "SUM"
Disp "SUM"
Line 2,982: Line 5,633:
Disp "REMAINDER"
Disp "REMAINDER"
Pause A-B*int(A/B)
Pause A-B*int(A/B)
</syntaxhighlight>
</lang>


=={{header|TI-89 BASIC}}==
=={{header|TI-89 BASIC}}==


<lang ti89b>Local a, b
<syntaxhighlight lang="ti89b">Local a, b
Prompt a, b
Prompt a, b
Disp "Sum: " & string(a + b)
Disp "Sum: " & string(a + b)
Line 2,992: Line 5,643:
Disp "Product: " & string(a * b)
Disp "Product: " & string(a * b)
Disp "Integer quotient: " & string(intDiv(a, b))
Disp "Integer quotient: " & string(intDiv(a, b))
Disp "Remainder: " & string(remain(a, b))</lang>
Disp "Remainder: " & string(remain(a, b))</syntaxhighlight>


=={{header|Toka}}==
=={{header|Toka}}==


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


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
$$ MODE TUSCRIPT
a=5
a=5
Line 3,013: Line 5,664:
c=a/b
c=a/b
c=a%b
c=a%b
</syntaxhighlight>
</lang>
{{out}}
Output:
<pre>
<pre>
a=5
a=5
Line 3,036: Line 5,687:
{{works with|Bourne Shell}}
{{works with|Bourne Shell}}
{{works with|Almquist SHell}}
{{works with|Almquist SHell}}
<lang bash>#!/bin/sh
<syntaxhighlight lang="bash">#!/bin/sh
read a; read b;
read a; read b;
echo "a+b = " `expr $a + $b`
echo "a+b = " `expr $a + $b`
Line 3,042: Line 5,693:
echo "a*b = " `expr $a \* $b`
echo "a*b = " `expr $a \* $b`
echo "a/b = " `expr $a / $b` # truncates towards 0
echo "a/b = " `expr $a / $b` # truncates towards 0
echo "a mod b = " `expr $a % $b` # same sign as first operand</lang>
echo "a mod b = " `expr $a % $b` # same sign as first operand</syntaxhighlight>


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.
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.
Line 3,051: Line 5,702:
{{works with|pdksh|5.2.14}}
{{works with|pdksh|5.2.14}}
{{works with|Z SHell}}
{{works with|Z SHell}}
<lang bash>#!/bin/sh
<syntaxhighlight lang="bash">#!/bin/sh
read a; read b;
read a; read b;
echo "a+b = $((a+b))"
echo "a+b = $((a+b))"
Line 3,057: Line 5,708:
echo "a*b = $((a*b))"
echo "a*b = $((a*b))"
echo "a/b = $((a/b))" # truncates towards 0
echo "a/b = $((a/b))" # truncates towards 0
echo "a mod b = $((a%b))" # same sign as first operand</lang>
echo "a mod b = $((a%b))" # same sign as first operand</syntaxhighlight>


Note: spaces inside the ''$((...))'' are optional and not required; the ''$((...))'' can be inside or outside the double quotes, but the `...` expressions from the previous example can also be inside or outside the double quotes.
Note: spaces inside the ''$((...))'' are optional and not required; the ''$((...))'' can be inside or outside the double quotes, but the `...` expressions from the previous example can also be inside or outside the double quotes.

=={{header|Ursa}}==
<syntaxhighlight lang="ursa">#
# integer arithmetic
#

decl int x y
out "number 1: " console
set x (in int console)
out "number 2: " console
set y (in int console)

out "\nsum:\t" (int (+ x y)) endl console
out "diff:\t" (int (- x y)) endl console
out "prod:\t" (int (* x y)) endl console
# quotient doesn't round at all, but the int function rounds up
out "quot:\t" (int (/ x y)) endl console
# mod takes the sign of x
out "mod:\t" (int (mod x y)) endl console</syntaxhighlight>

Sample session:
<pre>number 1: 15
number 2: 7

sum: 22
diff: 8
prod: 105
quot: 2
mod: 1</pre>


=={{header|VBA}}==
=={{header|VBA}}==
<syntaxhighlight lang="vb">
<lang vb>
'Arithmetic - Integer
'Arithmetic - Integer
Sub RosettaArithmeticInt()
Sub RosettaArithmeticInt()
Line 3,080: Line 5,760:
Next opr
Next opr
End Sub
End Sub
</syntaxhighlight>
</lang>


=={{header|VBScript}}==
=={{header|VBScript}}==
Line 3,086: Line 5,766:


===Implementation===
===Implementation===
<lang vb>option explicit
<syntaxhighlight lang="vb">option explicit
dim a, b
dim a, b
wscript.stdout.write "A? "
wscript.stdout.write "A? "
Line 3,102: Line 5,782:
wscript.echo "a \ b=", a \ b
wscript.echo "a \ b=", a \ b
wscript.echo "a mod b=", a mod b
wscript.echo "a mod b=", a mod b
wscript.echo "a ^ b=", a ^ b</lang>
wscript.echo "a ^ b=", a ^ b</syntaxhighlight>


===Another Implementation===
===Another Implementation===
Gives the same output for the same input. Inspired by Python version.
Gives the same output for the same input. Inspired by Python version.
<lang vb>option explicit
<syntaxhighlight lang="vb">option explicit
dim a, b
dim a, b
wscript.stdout.write "A? "
wscript.stdout.write "A? "
Line 3,119: Line 5,799:
for each op in split("+ - * / \ mod ^", " ")
for each op in split("+ - * / \ mod ^", " ")
wscript.echo "a",op,"b=",eval( "a " & op & " b")
wscript.echo "a",op,"b=",eval( "a " & op & " b")
next</lang>
next</syntaxhighlight>


===Invocation===
===Invocation===
Line 3,136: Line 5,816:


=={{header|Vedit macro language}}==
=={{header|Vedit macro language}}==
<lang vedit>#1 = Get_Num("Give number a: ")
<syntaxhighlight lang="vedit">#1 = Get_Num("Give number a: ")
#2 = Get_Num("Give number b: ")
#2 = Get_Num("Give number b: ")
Message("a + b = ") Num_Type(#1 + #2)
Message("a + b = ") Num_Type(#1 + #2)
Line 3,142: Line 5,822:
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)</lang>
Message("a % b = ") Num_Type(#1 % #2)</syntaxhighlight>


=={{header|Verilog}}==
<syntaxhighlight lang="verilog">module main;
integer a, b;
integer suma, resta, producto;
integer division, resto, expo;
initial begin
a = -12;
b = 7;
suma = a + b;
resta = a - b;
producto = a * b;
division = a / b;
resto = a % b;
expo = a ** b;
$display("Siendo dos enteros a = -12 y b = 7");
$display(" suma de a + b = ", suma);
$display(" resta de a - b = ", resta);
$display(" producto de a * b = ", producto);
$display(" división de a / b = ", division);
$display(" resto de a mod b = ", resto);
$display("exponenciación a ^ b = ", expo);
$finish ;
end
endmodule</syntaxhighlight>


=={{header|Vim Script}}==
=={{header|Vim Script}}==
<lang vim>let a = float2nr(input("Number 1: ") + 0)
<syntaxhighlight lang="vim">let a = float2nr(input("Number 1: ") + 0)
let b = float2nr(input("Number 2: ") + 0)
let b = float2nr(input("Number 2: ") + 0)
echo "\nSum: " . (a + b)
echo "\nSum: " . (a + b)
Line 3,154: Line 5,863:
" The sign of the result of the remainder operation matches the sign of
" The sign of the result of the remainder operation matches the sign of
" the first operand
" the first operand
echo "Remainder: " . (a % b)</lang>
echo "Remainder: " . (a % b)</syntaxhighlight>


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
<lang vbnet>Imports System.Console
<syntaxhighlight lang="vbnet">Imports System.Console
Module Module1
Module Module1
Sub Main
Sub Main
Line 3,170: Line 5,879:
WriteLine("Exponent " & a ^ b)
WriteLine("Exponent " & a ^ b)
End Sub
End Sub
End Module</lang>
End Module</syntaxhighlight>

=={{header|V (Vlang)}}==
<syntaxhighlight lang="go">// Arithmetic-integer in V (Vlang)
// Tectonics: v run arithmetic-integer.v
module main
import math
import os

// starts here
pub fn main() {
mut a := 0
mut b := 0

// get numbers from console
print("Enter two integer numbers, separated by a space: ")
text := os.get_raw_line()
values := text.split(' ')
a = values[0].int()
b = values[1].int()

// 4 basics, remainder, no exponentiation operator
println("values: a $a, b $b")
println("sum: a + b = ${a + b}")
println("difference: a - b = ${a - b}")
println("product: a * b = ${a * b}")
println("integer quotient: a / b = ${a / b}, truncation")
println("remainder: a % b = ${a % b}, sign follows dividend")

println("no exponentiation operator")
println(" math.pow: pow(a,b) = ${math.pow(a,b)}")
}</syntaxhighlight>

{{out}}
<pre>prompt$ v run arithmetic-integer.v
Enter two integer numbers, separated by a space: -5 3
values: a -5, b 3
sum: a + b = -2
difference: a - b = -8
product: a * b = -15
integer quotient: a / b = -1, truncation
remainder: a % b = -2, sign follows dividend
no exponentiation operator
math.pow: pow(a,b) = -125</pre>


=={{header|Wart}}==
=={{header|Wart}}==
<lang python>a <- (read)
<syntaxhighlight lang="python">a <- (read)
b <- (read)
b <- (read)
prn "sum: " a+b
prn "sum: " a+b
Line 3,181: Line 5,933:
prn "integer quotient: " (int a/b)
prn "integer quotient: " (int a/b)
prn "remainder: " a%b
prn "remainder: " a%b
prn "exponent: " a^b</lang>
prn "exponent: " a^b</syntaxhighlight>

=={{header|Wren}}==
In Wren the quotient operator '/' does not round but, when the ''floor'' method is applied to the result, it rounds to the lower integer.

The sign of the remainder operator '%' matches the sign of the first operand.
<syntaxhighlight lang="wren">import "io" for Stdin, Stdout
System.write("first number: ")
Stdout.flush()
var a = Num.fromString(Stdin.readLine())
System.write("second number: ")
Stdout.flush()
var b = Num.fromString(Stdin.readLine())
System.print("sum: %(a + b)")
System.print("difference: %(a - b)")
System.print("product: %(a * b)")
System.print("integer quotient: %((a / b).floor)")
System.print("remainder: %(a % b)")
System.print("exponentiation: %(a.pow(b))")</syntaxhighlight>

{{out}}
Sample input/output:
<pre>
first number: 4
second number: 3
sum: 7
difference: 1
product: 12
integer quotient: 1
remainder: 1
exponentiation: 64
</pre>

=={{header|x86 Assembly}}==
Input and output would be OS-specific and are not implemented. This routine works on the 16-bit 8086, as well as on its 32-bit and 64-bit successors: it could be trivially modified to perform 32-bit or 64-bit arithmetic on machines where those are supported. The quotient is truncated towards zero; the remainder takes its sign from the first operand.
<syntaxhighlight lang="asm">arithm: mov cx, a
mov bx, b
xor dx, dx
mov ax, cx
add ax, bx
mov sum, ax
mov ax, cx
imul bx
mov product, ax
mov ax, cx
sub ax, bx
mov difference, ax
mov ax, cx
idiv bx
mov quotient, ax
mov remainder, dx

ret</syntaxhighlight>

=={{header|XLISP}}==
<syntaxhighlight lang="xlisp">(DEFUN INTEGER-ARITHMETIC ()
(DISPLAY "Enter two integers separated by a space.")
(NEWLINE)
(DISPLAY "> ")
(DEFINE A (READ))
(DEFINE B (READ))
(DISPLAY `(SUM ,(+ A B)))
(NEWLINE)
(DISPLAY `(DIFFERENCE ,(- A B)))
(NEWLINE)
(DISPLAY `(PRODUCT ,(* A B)))
(NEWLINE)
(DISPLAY `(QUOTIENT ,(QUOTIENT A B))) ; truncates towards zero
(NEWLINE)
(DISPLAY `(REMAINDER ,(REM A B))) ; takes sign of first operand
(NEWLINE)
(DISPLAY `(EXPONENTIATION ,(EXPT A B))))</syntaxhighlight>


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes;
<syntaxhighlight lang="xpl0">include c:\cxpl\codes;
int A, B;
int A, B;
[A:= IntIn(0);
[A:= IntIn(0);
Line 3,193: Line 6,020:
IntOut(0, A/B); CrLf(0); \truncates toward zero
IntOut(0, A/B); CrLf(0); \truncates toward zero
IntOut(0, rem(0)); CrLf(0); \remainder's sign matches first operand (A)
IntOut(0, rem(0)); CrLf(0); \remainder's sign matches first operand (A)
]</lang>
]</syntaxhighlight>


=={{header|XSLT}}==
=={{header|XSLT}}==
<lang xml><xsl:template name="arithmetic">
<syntaxhighlight lang="xml"><xsl:template name="arithmetic">
<xsl:param name="a">5</xsl:param>
<xsl:param name="a">5</xsl:param>
<xsl:param name="b">2</xsl:param>
<xsl:param name="b">2</xsl:param>
Line 3,204: Line 6,031:
<fo:block>a / b = <xsl:value-of select="round($a div $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>
<fo:block>a mod b = <xsl:value-of select="$a mod $b"/></fo:block>
</xsl:template></lang>
</xsl:template></syntaxhighlight>


=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">input "ingrese un numero? " a
input "ingrese otro numero? " b

print "suma ", a, " + ", b, " = ", (a + b)
print "resta ", a, " - ", b, " = ", (a - b)
print "producto ", a, " * ", b, " = ", (a * b)
print "division ", a, " \ ", b, " = ", int(a / b)
print "modulo ", a, " % ", b, " = ", mod(a, b)
print "potencia ", a, " ^ ", b, " = ", (a ^ b)
end</syntaxhighlight>



=={{header|Yorick}}==
=={{header|Yorick}}==
<lang yorick>x = y = 0;
<syntaxhighlight lang="yorick">x = y = 0;
read, x, y;
read, x, y;
write, "x + y =", x + y;
write, "x + y =", x + y;
Line 3,214: Line 6,055:
write, "x / y =", x / y; // rounds toward zero
write, "x / y =", x / y; // rounds toward zero
write, "x % y =", x % y; // remainder; matches sign of first operand when operands' signs differ
write, "x % y =", x % y; // remainder; matches sign of first operand when operands' signs differ
write, "x ^ y =", x ^ y; // exponentiation</lang>
write, "x ^ y =", x ^ y; // exponentiation</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>x,y:=ask("Two ints: ").split(" ").apply("toInt");
<syntaxhighlight lang="zkl">x,y:=ask("Two ints: ").split(" ").apply("toInt");
println("x+y = ",x + y);
println("x+y = ",x + y);
println("x-y = ",x - y);
println("x-y = ",x - y);
Line 3,223: Line 6,064:
println("x/y = ",x / y); // rounds toward zero
println("x/y = ",x / y); // rounds toward zero
println("x%y = ",x % y); // remainder; matches sign of first operand when operands' signs differ
println("x%y = ",x % y); // remainder; matches sign of first operand when operands' signs differ
println("x.divr(y) = ",x.divr(y)); // (x/y,remainder); sign as above</lang>
println("x.divr(y) = ",x.divr(y)); // (x/y,remainder); sign as above</syntaxhighlight>

=={{header|zonnon}}==
<syntaxhighlight lang="zonnon">
module Main;
var
i,j: integer;
begin
write("A integer?:");readln(i);
write("another?: ");readln(j);
writeln("sum: ",i + j);
writeln("difference: ", i - j);
writeln("product: ", i * j);
writeln("quotient: ", i div j);
writeln("remainder: ", i mod j);
end Main.
</syntaxhighlight>
{{Out}}
<pre>
A integer?:2
another?: 3
sum: 5
difference: -1
product: 6
quotient: 0
remainder: 2
</pre>

=={{header|ZX Spectrum Basic}}==
<syntaxhighlight lang="zxbasic">5 LET a=5: LET b=3
10 PRINT a;" + ";b;" = ";a+b
20 PRINT a;" - ";b;" = ";a-b
30 PRINT a;" * ";b;" = ";a*b
40 PRINT a;" / ";b;" = ";INT (a/b)
50 PRINT a;" mod ";b;" = ";a-INT (a/b)*b
60 PRINT a;" to the power of ";b;" = ";a^b
</syntaxhighlight>

Latest revision as of 10:12, 29 December 2023

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:

Integer Operations
Arithmetic | Comparison

Boolean Operations
Bitwise | Logical

String Operations
Concatenation | Interpolation | Comparison | Matching

Memory Operations
Pointers & references | Addresses

Task

Get two integers from the user,   and then (for those two integers), display their:

  •   sum
  •   difference
  •   product
  •   integer quotient
  •   remainder
  •   exponentiation   (if the operator exists)


Don't include error handling.

For quotient, indicate how it rounds   (e.g. towards zero, 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.

Bonus: Include an example of the integer `divmod` operator. For example: as in #Haskell, #Python and #ALGOL 68

0815

|~>|~#:end:>
<:61:x<:3d:=<:20:$==$~$=${~>%<:2c:~$<:20:~$
<:62:x<:3d:=<:20:$==$~$=${~>%<:a:~$$
<:61:x<:2b:=<:20:$==$~$=$<:62:x<:3d:=<:20:$==$~$=${x{x~>~>~+%<:a:~$
<:61:x<:2d:=<:20:$==$~$=$<:62:x<:3d:=<:20:$==$~$=${x{x~>~>~-%<:a:~$
<:61:x<:2a:=<:20:$==$~$=$<:62:x<:3d:=<:20:$==$~$=${x{x~>~>~*%<:a:~$
<:61:x<:2f:=<:20:$==$~$=$<:62:x<:3d:=<:20:$==$~$=${x{x~>~>~/%<:a:~$
<:61:x<:25:=<:20:$==$~$=$<:62:x<:3d:=<:20:$==$~$=${x{x~>~>~/=%<:a:~$
{~>>{x<:1:-^:u:
<:61:x<:5e:=<:20:$==$~$$=$<:62:x<:3D:=<:20:$==$~$=${{~%#:end:
}:u:=>{x{=>~*>{x<:2:-#:ter:
}:ml:x->{x{=>~*>{x<:1:-#:ter:^:ml:
}:ter:<:61:x<:5e:=<:20:$==$~$$=$<:62:x<:3D:=<:20:$==$~$=${{~%
Output:
a = 6, b = 4

a + b = A
a - b = 2
a * b = 18
a / b = 1
a % b = 2
a ^^ b = 510

11l

V a = Int(input())
V b = Int(input())

print(‘a + b = ’(a + b))
print(‘a - b = ’(a - b))
print(‘a * b = ’(a * b))
print(‘a / b = ’(a I/ b))
print(‘a % b = ’(a % b))
print(‘a ^ b = ’(a ^ b))

360 Assembly

From the principles of operation: Operands are signed and 32 bits long. Negative quantities are held in two's-complement form.
Multiplication:
The product of the multiplier (the second operand) and the multiplicand (the first operand) replaces the multiplicand. Both multiplier and multiplicand are 32-bit signed integers. The product is always a 64-bit signed integer and occupies an even/odd register pair.
Division:
The dividend (first operand) is divided by the divisor (second operand) and replaced by the quotient and remainder. The dividend is a 64-bit signed integer and occupies the even/odd pair of registers. A 32-bit signed remainder and a 32-bit signed quotient replace the dividend in the even-numbered and odd-numbered registers, respectively. The sign of the quotient is determined by the rules of algebra. The remainder has the same sign as the dividend.

*        Arithmetic/Integer        04/09/2015
ARITHINT CSECT
         USING  ARITHINT,R12
         LR     R12,R15
ADD      L      R1,A
         A      R1,B               r1=a+b
         XDECO  R1,BUF
         MVI    BUF,C'+'
         XPRNT  BUF,12
SUB      L      R1,A
         S      R1,B               r1=a-b
         XDECO  R1,BUF
         MVI    BUF,C'-'
         XPRNT  BUF,12
MUL      L      R1,A 
         M      R0,B               r0r1=a*b
         XDECO  R1,BUF             so r1 has the lower part
         MVI    BUF,C'*'
         XPRNT  BUF,12
DIV      L      R0,A
         SRDA   R0,32              to shift the sign
         D      R0,B               r1=a/b and r0 has the remainder
         XDECO  R1,BUF             so r1 has quotient
         MVI    BUF,C'/'
         XPRNT  BUF,12
MOD      L      R0,A
         SRDA   R0,32              to shift the sign
         D      R0,B               r1=a/b and r0 has the remainder
         XDECO  R0,BUF             so r0 has the remainder
         MVI    BUF,C'R'
         XPRNT  BUF,12
RETURN   XR     R15,R15
         BR     R14
         CNOP   0,4
A        DC     F'53'
B        DC     F'11'
BUF      DC     CL12' '
         YREGS
         END    ARITHINT

Inputs are in the code: a=53, b=11

Output:
+         64
-         42
*        583
/          4
R          9

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.

68000 Assembly

ADD.L D0,D1 ; add two numbers
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
SUB.L D1,D0 ; subtract D1 from D0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
MULU D0,D1  ; multiply two unsigned numbers. Use MULS for signed numbers
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
DIVU D1,D0  ; Divide D0 by D1. Use DIVS for signed numbers. Upper two bytes of D0 are the remainder, lower two are the integer quotient.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
MODULUS:
DIVU D1,D0
SWAP D0     ;swap the order of the 16-bit halves of D0.
RTS

Exponentiation doesn't exist but can be implemented in a similar fashion to multiplication on the 6502:

Exponent:
;raises D0 to the D1 power. No overflow protection.
MOVE.L D0,D2
SUBQ.L #1,D1
loop_exponent:
MULU D0,D2
DBRA D1,loop_exponent
;output is in D2
RTS

AArch64 Assembly

Works with: as version Raspberry Pi 3B version Buster 64 bits
/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program arith64.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc" 

/***********************/
/* Initialized data */
/***********************/
.data
szMessError:          .asciz " Two numbers in command line please ! \n"       // message
szRetourLigne:        .asciz "\n"
szMessResult:         .asciz "resultat : @ \n"      // message result
sMessValeur:          .fill 12, 1, ' '
                      .asciz "\n"
szMessAddition:       .asciz "Addition "
szMessSoustraction:   .asciz "soustraction :"
szMessMultiplication: .asciz "multiplication :"
szMessDivision:       .asciz "division :"
szMessReste:          .asciz "remainder :"
 
/***********************/
/* No Initialized data */
/***********************/
.bss
qValeur:            .skip  8        // reserve 8 bytes in memory
sZoneConv:          .skip 30  
.text
.global main 
main:
    mov fp,sp                   // fp <- stack address
    ldr x0,[fp]                 // recup number of parameter in command line
    cmp x0,3
    blt error
    ldr x0,[fp,16]              // adresse of 1er number
    bl conversionAtoD
    mov x3,x0
    ldr x0,[fp,24]              // adresse of 2eme number
    bl conversionAtoD
    mov x4,x0
                                // addition
    add x0,x3,x4
    ldr x1,qAdrsZoneConv        // result in x0
    bl conversion10S            // call function with 2 parameter (x0,x1)
    ldr x0,qAdrszMessAddition
    bl affichageMess            // display message
    ldr x0,qAdrszMessResult
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc       // insert result at @ character
    bl affichageMess            // display message
    ldr x0,qAdrsZoneConv
                                // soustraction
    sub x0,x3,x4
    ldr x1,qAdrsZoneConv        // result in x0
    bl conversion10S            // call function with 2 parameter (x0,x1)
    ldr x0,qAdrszMessSoustraction
    bl affichageMess            // display message
    ldr x0,qAdrszMessResult
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc       // insert result at @ character
    bl affichageMess            // display message
    ldr x0,qAdrsZoneConv
                                // multiplication
    mul x0,x3,x4
    ldr x1,qAdrsZoneConv        // result in x0
    bl conversion10S            // call function with 2 parameter (x0,x1)
    ldr x0,qAdrszMessMultiplication
    bl affichageMess            // display message
    ldr x0,qAdrszMessResult
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc       // insert result at @ character
    bl affichageMess            // display message
    ldr x0,qAdrsZoneConv
                                // division 
    mov x0,x3
    mov x1,x4
    udiv x0,x3,x4               // quotient
    msub x3,x0,x4,x3            // remainder x3 = x3 - (x0*x4)
    ldr x1,qAdrsZoneConv        // result in x0
    bl conversion10S            // call function with 2 parameter (x0,x1)
    ldr x0,qAdrszMessDivision
    bl affichageMess            // display message
    ldr x0,qAdrszMessResult
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc       // insert result at @ character
    bl affichageMess            // display message
    ldr x0,qAdrsZoneConv

    mov x0,x3                   // remainder
    ldr x1,qAdrsZoneConv        // result in x0
    bl conversion10S            // call function with 2 parameter (x0,x1)
    ldr x0,qAdrszMessReste
    bl affichageMess            // display message
    ldr x0,qAdrszMessResult
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc       // insert result at @ character
    bl affichageMess            // display message
    ldr x0,qAdrsZoneConv
 
    mov x0,0                    // return code
    b 100f
error:
    ldr x0,qAdrszMessError
    bl affichageMess            // call function with 1 parameter (x0)
    mov x0,1                    // return code
100:                            // end of  program
    mov x8,EXIT                 // request to exit program
    svc 0                       // perform the system call
qAdrsMessValeur:          .quad sMessValeur    
qAdrszMessResult:         .quad szMessResult
qAdrszMessError:          .quad szMessError
qAdrszMessAddition:       .quad szMessAddition
qAdrszMessSoustraction:   .quad szMessSoustraction
qAdrszMessMultiplication: .quad szMessMultiplication
qAdrszMessDivision:       .quad szMessDivision
qAdrszMessReste:          .quad szMessReste
qAdrsZoneConv:            .quad sZoneConv
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
Output:
pi@debian-buster-64:~/asm64/rosetta/asm3 $ arith64 101 25
Addition resultat : +126
soustraction :resultat : +76
multiplication :resultat : +2525
division :resultat : +4
remainder :resultat : +1

ABAP

report zz_arithmetic no standard page heading.

" Read in the two numbers from the user.
selection-screen begin of block input.
  parameters: p_first type i,
              p_second type i.
selection-screen end of block input.

" Set the text value that is displayed on input request.
at selection-screen output.
  %_p_first_%_app_%-text  = 'First Number: '.
  %_p_second_%_app_%-text = 'Second Number: '.

end-of-selection.
  data: lv_result type i.
  lv_result = p_first + p_second.
  write: / 'Addition:', lv_result.
  lv_result = p_first - p_second.
  write: / 'Substraction:', lv_result.
  lv_result = p_first * p_second.
  write: / 'Multiplication:', lv_result.
  lv_result = p_first div p_second.
  write: / 'Integer quotient:', lv_result. " Truncated towards zero.
  lv_result = p_first mod p_second.
  write: / 'Remainder:',  lv_result.

ACL2

:set-state-ok t

(defun get-two-nums (state)
   (mv-let (_ a state)
           (read-object *standard-oi* state)
      (declare (ignore _))
      (mv-let (_ b state)
              (read-object *standard-oi* state)
         (declare (ignore _))
         (mv a b state))))

(defun integer-arithmetic (state)
   (mv-let (a b state)
           (get-two-nums state)
      (mv state
          (progn$ (cw "Sum:        ~x0~%" (+ a b))
                  (cw "Difference: ~x0~%" (- a b))
                  (cw "Product:    ~x0~%" (* a b))
                  (cw "Quotient:   ~x0~%" (floor a b))
                  (cw "Remainder:  ~x0~%" (mod a b))))))

Action!

DEFINE NO_KEY="255"
DEFINE KEY_Y="43"
DEFINE KEY_N="35"

PROC Main()
  BYTE CH=$02FC ;Internal hardware value for last key pressed
  BYTE k
  INT a,b

  DO
    Print("Input integer value a=")
    a=InputI()
    Print("Input integer value b=")
    b=InputI()

    PrintF("a+b=%I%E",a+b)
    PrintF("a-b=%I%E",a-b)
    PrintF("a*b=%I%E",a*b)
    PrintF("a/b=%I%E",a/b)
    PrintF("a MOD b=%I%E",a MOD b)
    
    PutE()
    PrintE("Again? (Y/N)")

    CH=NO_KEY ;Flush the keyboard
    DO
      k=CH
    UNTIL k=KEY_Y OR k=KEY_N
    OD
    CH=NO_KEY ;Flush the keyboard

    IF k=KEY_N THEN
      EXIT
    FI
  OD
RETURN
Output:

Screenshot from Atari 8-bit computer

Input integer value a=3251
Input integer value b=15
a+b=3266
a-b=3236
a*b=-16771
a/b=216
a MOD b=11

Again? (Y/N)


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));
   Put_Line("a mod b = " & Integer'Image(A mod B)); -- Sign matches B
   Put_Line("remainder of a/b = " & Integer'Image(A rem B)); -- Sign matches A
   Put_Line("a**b = " & Integer'Image(A ** B));  

end Integer_Arithmetic;

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))

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 PLUS b = a+b = "gl$, a + b));
  printf(($"a MINUS b = a-b = "gl$, a - b));
  printf(($"a TIMES b = a*b = a×b = "gl$, a * b));
  printf(($"a DIV b = 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 PLUS b = a+b =                                 +468
a MINUS b = a-b =                                 +242
a TIMES b = a*b = a×b =                               +40115
a DIV b = 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 a non-standard '%:=' operator. This operator is equivalent to the OVERAB operator of the revised report, except it delivers the remainder as a result. So a '/:=' b sets a to the quotient of a%b and returns the remainder of a%b as a result (Note "%" is the division operator in Algol 68, not the modulo operator - it can also be written as OVER). This operator must be "stropped" i.e. enclosed in single quotes. eg.

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

Sets quotient to 3, remainder to 16.

ALGOL W

The Algol W integer division operator (called div) truncates towards zero.
The result of the modulo operator (called rem) has the sign of the first operand when the operands have different signs.

begin
    integer a, b;
    write( "Enter 2 integers> " );
    read( a, b );
    write( "a  +  b: ", a  +  b ); % addition         %
    write( "a  -  b: ", a  -  b ); % subtraction      %
    write( "a  *  b: ", a  *  b ); % multiplication   %
    write( "a  /  b: ", a div b ); % integer division %
    write( "a mod b: ", a rem b ); % modulo           %
    % the ** operator returns a real result even with integer operands  %
    % ( the right-hand operand must always be an integer, the left-hand %
    % operand can be integer, real or complex )                         %
    write( "a  ^  b: ", round( a ** b ) )
end.

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

APL

res  integer_arithmetic; l; r
  l  
  r  
  res  6 2  'sum' (l+r) 'diff' (l-r) 'prod' (l×r) 'quot' (l÷r) 'rem' (r|l) 'pow' (l*r)

Quotient will round down in this version.

AppleScript

set i1 to (text returned of (display dialog "Enter an integer value" default answer "")) as integer
set i2 to (text returned of (display dialog "Enter another integer value" default answer "")) as integer

set sum to i1 + i2
set diff to i1 - i2
set prod to i1 * i2
set quot to i1 div i2 -- Rounds towards zero.
set remainder to i1 mod i2 -- The result's sign matches the dividend's.
set exp to i1 ^ i2 -- The result's always a real.

return {|integers|:{i1, i2}, difference:diff, product:prod, quotient:quot, remainder:remainder, exponientiation:exp}
Output:
{|integers|:{-57, 2}, difference:-59, product:-114, quotient:-28, remainder:-1, exponientiation:3249.0}

ARM Assembly

Works with: as version Raspberry Pi
/* ARM assembly Raspberry PI  */
/*  program arith.s   */
/* Constantes    */
.equ STDOUT, 1
.equ WRITE,  4
.equ EXIT,   1

/***********************/
/* Initialized data */
/***********************/
.data
szMessError:      .asciz " Two numbers in command line please ! \n"       @ message
szRetourLigne: .asciz "\n"
szMessResult:  .asciz "Resultat "      @ message result
sMessValeur:   .fill 12, 1, ' '
                   .asciz "\n"
szMessAddition: .asciz "addition :"
szMessSoustraction: .asciz "soustraction :"
szMessMultiplication: .asciz "multiplication :"
szMessDivision: .asciz "division :"
szMessReste: .asciz "reste :"
   
/***********************/				   
/* No Initialized data */
/***********************/
.bss
iValeur:  .skip  4     @ reserve 4 bytes in memory

.text
.global main 
main:
    push {fp,lr}                @ save des  2 registres
    add fp,sp,#8                @ fp <- adresse début
    ldr r0,[fp]                 @ recup number of parameter in command line
    cmp r0,#3
    blt error
    ldr r0,[fp,#8]              @ adresse of 1er number
    bl conversionAtoD
    mov r3,r0
    ldr r0,[fp,#12]             @ adresse of 2eme number
    bl conversionAtoD
    mov r4,r0
    @ addition
    add r0,r3,r4
    ldr r1,iAdrsMessValeur      @ result in r0
    bl conversion10S            @ call function with 2 parameter (r0,r1)
    ldr r0,iAdrszMessResult
    bl affichageMess            @ display message
    ldr r0,iAdrszMessAddition
    bl affichageMess            @ display message
    ldr r0,iAdrsMessValeur
    bl affichageMess            @ display message
    @ soustraction
    sub r0,r3,r4
    ldr r1,=sMessValeur                 
    bl conversion10S            @ call function with 2 parameter (r0,r1)
    ldr r0,iAdrszMessResult
    bl affichageMess            @ display message
    ldr r0,iAdrszMessSoustraction
    bl affichageMess            @ display message
    ldr r0,iAdrsMessValeur
    bl affichageMess            @ display message

    @ multiplication
    mul r0,r3,r4
    ldr r1,=sMessValeur                 
    bl conversion10S            @ call function with 2 parameter (r0,r1)
    ldr r0,iAdrszMessResult
    bl affichageMess            @ display message
    ldr r0,iAdrszMessMultiplication
    bl affichageMess            @ display message
    ldr r0,iAdrsMessValeur
    bl affichageMess            @ display message
   
    @ division 
    mov r0,r3
    mov r1,r4
    bl division
    mov r0,r2                   @ quotient
    ldr r1,=sMessValeur                 
    bl conversion10S            @ call function with 2 parameter (r0,r1)
    ldr r0,iAdrszMessResult
    bl affichageMess            @ display message
    ldr r0,iAdrszMessDivision
    bl affichageMess            @ display message
    ldr r0,iAdrsMessValeur
    bl affichageMess            @ display message

    mov r0,r3                   @ remainder
    ldr r1,=sMessValeur                 
    bl conversion10S            @ call function with 2 parameter (r0,r1)
    ldr r0,iAdrszMessResult
    bl affichageMess            @ display message
    ldr r0,iAdrszMessReste
    bl affichageMess            @ display message
    ldr r0,iAdrsMessValeur
    bl affichageMess            @ display message
 
    mov r0, #0                  @ return code
    b 100f
error:
    ldr r0,iAdrszMessError
    bl affichageMess            @ call function with 1 parameter (r0)
    mov r0, #1                  @ return code
100: /* end of  program */
    mov r7, #EXIT               @ request to exit program
    swi 0                       @ perform the system call
iAdrsMessValeur: .int sMessValeur	
iAdrszMessResult: .int szMessResult
iAdrszMessError: .int szMessError
iAdrszMessAddition: .int szMessAddition
iAdrszMessSoustraction: .int szMessSoustraction
iAdrszMessMultiplication: .int szMessMultiplication
iAdrszMessDivision: .int szMessDivision
iAdrszMessReste: .int szMessReste
/******************************************************************/
/*     affichage des messages   avec calcul longueur              */ 
/******************************************************************/
/* r0 contient l adresse du message */
affichageMess:
    push {fp,lr}        /* save des  2 registres */ 
    push {r0,r1,r2,r7}  /* save des autres registres */
    mov r2,#0           /* compteur longueur */
1:                      /*calcul de la longueur */
    ldrb r1,[r0,r2]     /* recup octet position debut + indice */
    cmp r1,#0           /* si 0 c est fini */
    beq 1f
    add r2,r2,#1        /* sinon on ajoute 1 */
    b 1b
1:                      /* donc ici r2 contient la longueur du message */
    mov r1,r0           /* adresse du message en r1 */
    mov r0,#STDOUT      /* code pour écrire sur la sortie standard Linux */
    mov r7, #WRITE      /* code de l appel systeme 'write' */
    swi #0              /* appel systeme */
    pop {r0,r1,r2,r7}   /* restaur des autres registres */
    pop {fp,lr}         /* restaur des  2 registres */ 
    bx lr	        /* retour procedure */	
/***************************************************/
/*   conversion registre en décimal   signé  */
/***************************************************/
/* r0 contient le registre   */
/* r1 contient l adresse de la zone de conversion */
conversion10S:
    push {fp,lr}      /* save des  2 registres frame et retour */
    push {r0-r5}      /* save autres registres  */
    mov r2,r1         /* debut zone stockage */
    mov r5,#'+'       /* par defaut le signe est + */
    cmp r0,#0         /* nombre négatif ? */
    movlt r5,#'-'     /* oui le signe est - */
    mvnlt r0,r0       /* et inversion en valeur positive */
    addlt r0,#1
    mov r4,#10       /* longueur de la zone */
1:                   /* debut de boucle de conversion */
    bl divisionpar10 /* division  */
    add r1,#48       /* ajout de 48 au reste pour conversion ascii */	
    strb r1,[r2,r4]  /* stockage du byte en début de zone r5 + la position r4 */
    sub r4,r4,#1     /* position précedente */
    cmp r0,#0     
    bne 1b	     /* boucle si quotient different de zéro */
    strb r5,[r2,r4]  /* stockage du signe à la position courante */
    subs r4,r4,#1    /* position précedente */
    blt  100f        /* si r4 < 0  fin  */
                     /* sinon il faut completer le debut de la zone avec des blancs */
    mov r3,#' '      /* caractere espace */	
2:
    strb r3,[r2,r4]  /* stockage du byte  */
    subs r4,r4,#1    /* position précedente */
    bge 2b           /* boucle si r4 plus grand ou egal a zero */
100:                 /* fin standard de la fonction  */
    pop {r0-r5}      /*restaur des autres registres */
    pop {fp,lr}      /* restaur des  2 registres frame et retour  */
    bx lr   

/***************************************************/
/*   division par 10   signé                       */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*  
/* and   http://www.hackersdelight.org/            */
/***************************************************/
/* r0 contient le dividende   */
/* r0 retourne le quotient */	
/* r1 retourne le reste  */
divisionpar10:	
  /* r0 contains the argument to be divided by 10 */
   push {r2-r4}   /* save autres registres  */
   mov r4,r0 
   ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */
   smull r1, r2, r3, r0   /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */
   mov r2, r2, ASR #2     /* r2 <- r2 >> 2 */
   mov r1, r0, LSR #31    /* r1 <- r0 >> 31 */
   add r0, r2, r1         /* r0 <- r2 + r1 */
   add r2,r0,r0, lsl #2   /* r2 <- r0 * 5 */
   sub r1,r4,r2, lsl #1   /* r1 <- r4 - (r2 * 2)  = r4 - (r0 * 10) */
   pop {r2-r4}
   bx lr                  /* leave function */
   .align 4
.Ls_magic_number_10: .word 0x66666667
/******************************************************************/
/*     Conversion d une chaine en nombre stocké dans un registre  */ 
/******************************************************************/
/* r0 contient l adresse de la zone terminée par 0 ou 0A */
conversionAtoD:
    push {fp,lr}      /* save des  2 registres */ 
    push {r1-r7}      /* save des autres registres */
    mov r1,#0
    mov r2,#10        /* facteur */
    mov r3,#0         /* compteur */
    mov r4,r0         /* save de l adresse dans r4 */
    mov r6,#0         /* signe positif par defaut */
    mov r0,#0         /* initialisation à 0 */ 
1:                    /* boucle d élimination des blancs du debut */
    ldrb r5,[r4,r3]   /* chargement dans r5 de l octet situé au debut + la position */
    cmp r5,#0         /* fin de chaine -> fin routine */
    beq 100f
    cmp r5,#0x0A      /* fin de chaine -> fin routine */
    beq 100f
    cmp r5,#' '       /* blanc au début */
    bne 1f            /* non on continue */
    add r3,r3,#1      /* oui on boucle en avançant d un octet */
    b 1b
1:
    cmp r5,#'-'       /* premier caracteres est -    */
    moveq r6,#1       /* maj du registre r6 avec 1 */
    beq 3f            /* puis on avance à la position suivante */
2:                    /* debut de boucle de traitement des chiffres */
    cmp r5,#'0'       /* caractere n est pas un chiffre */
    blt 3f
    cmp r5,#'9'       /* caractere n est pas un chiffre */
    bgt 3f
                      /* caractère est un chiffre */
    sub r5,#48
    ldr r1,iMaxi      /*verifier le dépassement du registre  */  
    cmp r0,r1
    bgt 99f
    mul r0,r2,r0     /* multiplier par facteur */
    add r0,r5        /* ajout à r0 */
3:
    add r3,r3,#1     /* avance à la position suivante */
    ldrb r5,[r4,r3]  /* chargement de l octet */
    cmp r5,#0        /* fin de chaine -> fin routine */
    beq 4f
    cmp r5,#10       /* fin de chaine -> fin routine */
    beq 4f
    b 2b             /* boucler */ 
4:
    cmp r6,#1        /* test du registre r6 pour le signe */
    bne 100f
    mov r1,#-1
    mul r0,r1,r0    /* si negatif, on multiplie par -1 */
    b 100f
99:                 /* erreur de dépassement */
    ldr r1,=szMessErrDep
    bl   afficheerreur 
    mov r0,#0       /* en cas d erreur on retourne toujours zero */
100:
    pop {r1-r7}     /* restaur des autres registres */
    pop {fp,lr}     /* restaur des  2 registres */ 
    bx lr           /* retour procedure */	
/* constante programme */	
iMaxi: .int 1073741824	
szMessErrDep:  .asciz  "Nombre trop grand : dépassement de capacite de 32 bits. :\n"
.align 4
/*=============================================*/
/* division entiere non signée                */
/*============================================*/
division:
    /* r0 contains N */
    /* r1 contains D */
    /* r2 contains Q */
    /* r3 contains R */
    push {r4, lr}
    mov r2, #0              /* r2 ? 0 */
    mov r3, #0              /* r3 ? 0 */
    mov r4, #32             /* r4 ? 32 */
    b 2f
1:
    movs r0, r0, LSL #1    /* r0 ? r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1) */
    adc r3, r3, r3         /* r3 ? r3 + r3 + C. This is equivalent to r3 ? (r3 << 1) + C */
 
    cmp r3, r1             /* compute r3 - r1 and update cpsr */
    subhs r3, r3, r1       /* if r3 >= r1 (C=1) then r3 ? r3 - r1 */
    adc r2, r2, r2         /* r2 ? r2 + r2 + C. This is equivalent to r2 ? (r2 << 1) + C */
2:
    subs r4, r4, #1        /* r4 ? r4 - 1 */
    bpl 1b                 /* if r4 >= 0 (N=0) then branch to .Lloop1 */
 
    pop {r4, lr}
    bx lr

Arturo

a: to :integer input "give me the first number  : "
b: to :integer input "give me the second number : "

print [a "+" b "=" a+b]
print [a "-" b "=" a-b]
print [a "*" b "=" a*b]
print [a "/" b "=" a/b]
print [a "%" b "=" a%b]
print [a "^" b "=" a^b]
Output:
give me the first number  : 33
give me the second number : 6
33 + 6 = 39
33 - 6 = 27
33 * 6 = 198
33 / 6 = 5
33 % 6 = 3
33 ^ 6 = 12914679699


Asymptote

int a = -12;
int b = 7;

int suma = a + b;
int resta = a - b;
int producto = a * b;
real division = a / b;
int resto = a % b;
int expo = a ** b;

write("Siendo dos enteros a = -12 y b = 7");
write("       suma de a + b = ", suma);
write("      resta de a - b = ", resta);
write("   producto de a * b = ", producto);
write("   división de a / b = ", division);
write("   resto de a mod  b = ", resto);
write("exponenciación a ^ b = ", expo);

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

Avail

Method "arithmetic demo_,_" is 
[
    a : integer,
    b : integer
|
    Print: “a + b”;
    Print: “a - b”;
    Print: “a × b”; // or a * b
    Print: “a ÷ b”; // or a / b, rounds toward negative infinity
    Print: “a mod b”; // sign matches second argument
    Print: “a ^ b”;
];

AWK

/^[ \t]*-?[0-9]+[ \t]+-?[0-9]+[ \t]*$/ {
	print "add:", $1 + $2
	print "sub:", $1 - $2
	print "mul:", $1 * $2
	print "div:", int($1 / $2) # truncates toward zero
	print "mod:", $1 % $2      # same sign as first operand
	print "exp:", $1 ^ $2
	exit }

For division and modulus, Awk should act like C.

Exponentiation's note: With nawk or gawk, $1 ** $2 acts like $1 ^ $2. With mawk, $1 ** $2 is a syntax error. Nawk allows **, but its manual page only has ^. Gawk's manual warns, "The POSIX standard only specifies the use of `^' for exponentiation. For maximum portability, do not use the `**' operator."

BASIC

Applesoft BASIC

Same code as Commodore BASIC

BaCon

' Arthimetic/Integer
DECLARE a%, b%
INPUT "Enter integer A: ", a%
INPUT "Enter integer B: ", b%
PRINT

PRINT a%, " + ", b%, "     is ", a% + b%
PRINT a%, " - ", b%, "     is ", a% - b%
PRINT a%, " * ", b%, "     is ", a% * b%
PRINT a%, " / ", b%, "     is ", a% / b%, ", trucation toward zero"
PRINT "MOD(", a%, ", ", b%, ") is ", MOD(a%, b%), ", same sign as first operand"
PRINT "POW(", a%, ", ", b%, ") is ", INT(POW(a%, b%))

Chipmunk Basic

Works with: Chipmunk Basic version 3.6.4
10 input "Enter two integers separated by a comma: ";a,b
20 print "       Sum: ";a+b
30 print "Difference: ";a-b
40 print "   Product: ";a*b
50 print "  Quontent: ";int(a/b)
60 print " Remainder: ";a mod b
70 print "     Power: ";a^b

Commodore BASIC

10 INPUT "ENTER A NUMBER"; A%
20 INPUT "ENTER ANOTHER NUMBER"; B%
30 PRINT "ADDITION:";A%;"+";B%;"=";A%+B%
40 PRINT "SUBTRACTION:";A%;"-";B%;"=";A%-B%
50 PRINT "MULTIPLICATION:";A%;"*";B%;"=";A%*B%
60 PRINT "INTEGER DIVISION:";A%;"/";B%;"=";INT(A%/B%)
70 PRINT "REMAINDER OR MODULO:";A%;"%";B%;"=";A%-INT(A%/B%)*B%
80 PRINT "POWER:";A%;"^";B%;"=";A%^B%

GW-BASIC

Works with: PC-BASIC version any
Works with: BASICA
10 INPUT "Enter two integers separated by a comma: ";A, B
20 PRINT "       Sum:"; A + B
30 PRINT "Difference:"; A - B
40 PRINT "   Product:"; A * B
50 PRINT "  Quontent:"; A \ B
60 PRINT " Remainder:"; A MOD B
70 PRINT "     Power:"; A ^ B

Minimal BASIC

10 PRINT "ENTER A INTEGER"
20 INPUT A
30 PRINT "ENTER ANOTHER INTEGER"
40 INPUT B
50 PRINT "       SUM: "; A + B
60 PRINT "DIFFERENCE: "; A - B
70 PRINT "   PRODUCT: "; A * B
80 PRINT "  QUONTENT: "; INT(A / B)
90 PRINT " REMAINDER: "; A - INT(A / B ) * B
100 PRINT "     POWER:"; A ^ B
110 END

MSX Basic

Works with: MSX BASIC version any
10 INPUT "Enter two integers separated by a comma: ";A, B
20 PRINT "       Sum:"; A + B
30 PRINT "Difference:"; A - B
40 PRINT "   Product:"; A * B
50 PRINT "  Quontent:"; A \ B
60 PRINT " Remainder:"; A MOD B
70 PRINT "     Power:"; A ^ B

Quite BASIC

10 INPUT "enter a integer"; A
20 INPUT "enter another integer"; B
30 PRINT "       Sum: "; A + B
40 PRINT "Difference: "; A - B
50 PRINT "   Product: "; A * B
60 PRINT "  Quontent: "; INT(A / B)
70 PRINT " Remainder: "; A - INT(A / B ) * B

Tiny BASIC

    LET A = 5
    LET B = 3
    PRINT "A = ", A, ",  B = ", B
    PRINT ""
    PRINT A," + ",B," = ", A+B
    PRINT A," - ",B," = ", A-B
    PRINT A," * ",B," = ", A*B
    PRINT A," / ",B," = ", A/B
    PRINT A," % ",B," = ", A-(A/B)*B
    REM Exponent calculation
    LET X = 1
    LET E = 0
10  IF X >= B THEN GOTO 30
    LET T = E
    IF E < A THEN LET E = A*A
    IF T < A THEN GOTO 20
    IF E >= A THEN LET E = E*A 
20  LET X = X+1
    GOTO 10
30  PRINT A," ^ ",B," = ", E
    END

True BASIC

! RosettaCode: Integer Arithmetic
! True BASIC v6.007
! Translated from BaCon example.
PROGRAM Integer_Arithmetic
	INPUT PROMPT "Enter integer A: ": a
	INPUT PROMPT "Enter integer B: ": b
	PRINT
	PRINT a;" + ";b;" is ";a+b
	PRINT a;" - ";b;" is ";a-b
	PRINT a;" * ";b;" is ";a*b
	PRINT a;" / ";b;" is ";INT(a/b);
	PRINT "MOD(";a;", ";b;") is "; MOD(a,b)
	PRINT "POW(";a;", ";b;") is ";INT(a^b)
	GET KEY done
END

QBasic

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

XBasic

Works with: Windows XBasic
PROGRAM  "IntegerArithmetic"
VERSION  "0.0000"

DECLARE FUNCTION  Entry ()

FUNCTION  Entry ()
  a$ = INLINE$("Enter integer A: ")
  a = SLONG(a$)
  b$ = INLINE$("Enter integer B: ")
  b = SLONG(b$)
  PRINT
  PRINT "       Sum:"; a + b
  PRINT "Difference:"; a - b
  PRINT "   Product:"; a * b
  PRINT "  Quontent:"; a / b
  PRINT " Remainder:"; a MOD b
  PRINT "     Power:"; a ** b
END FUNCTION
END PROGRAM

BASIC256

input "enter a number ?", a
input "enter another number ?", b

print "addition " + a + " + " + b + " = " + (a + b)
print "subtraction " + a + " - " + b + " = " + (a - b)
print "multiplication " + a + " * " + b + " = " + (a * b)
print "integer division " + a + " \ " + b + " = " + (a \ b)
print "remainder or modulo " + a + " % " + b + " = " + (a % b)
print "power " + a + " ^ " + b + " = " + (a ^ b)

Batch File

Works with: Windows 7 version or later, haven't checked earlier versions
set /p equation=
set /a result=%equation%
echo %result%
pause

BBC BASIC

      INPUT "Enter the first integer: " first%
      INPUT "Enter the second integer: " second%
      
      PRINT "The sum is " ; first% + second%
      PRINT "The difference is " ; first% - second%
      PRINT "The product is " ; first% * second%
      PRINT "The integer quotient is " ; first% DIV second% " (rounds towards 0)"
      PRINT "The remainder is " ; first% MOD second% " (sign matches first operand)"
      PRINT "The first raised to the power of the second is " ; first% ^ second%

bc

define f(a, b) {
	"add: "; a + b
	"sub: "; a - b
	"mul: "; a * b
	"div: "; a / b  /* truncates toward zero */
	"mod: "; a % b  /* same sign as first operand */
	"pow: "; a ^ b
}

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="<

BQN

•Out "Enter number 1: "
a ← •BQN •GetLine @
•Out "Enter number 2: "
b ← •BQN •GetLine @

•Show a + b
•Show a - b
•Show a × b
•Show a ÷ b
•Show b | a
•Show a ⋆ b
Enter number 1:
12
Enter number 2:
2
14
10
24
6
0
144


Bracmat

The remainder returned by mod is non-negative. Furthermore, div$(!a.!d)*!d+mod$(!a.!d):!a for all integer !a and !d, !d:~0.

  ( enter
  =     put$"Enter two integer numbers, separated by space:"
      & get':(~/#?k_~/#?m|quit:?k)
    |     out
        $ "You must enter two integer numbers! Enter \"quit\" if you don't know how to do that."
      & !enter
  )
& !enter
& !k:~quit
& out$("You entered" !k and !m ". Now look:")
& out$("Sum:" !k+!m)
& out$("Difference:" !k+-1*!m)
& out$("Product:" !k*!m)
& out$("Integer division:" div$(!k.!m))
& out$("Remainder:" mod$(!k.!m))
& out$("Exponentiation:" !k^!m)
& done;

Brat

Inspired by the second VBScript version.

x = ask("First number: ").to_i
y = ask("Second number: ").to_i

#Division uses floating point
#Remainder uses sign of right hand side
[:+ :- :* :/ :% :^].each { op |
  p "#{x} #{op} #{y} = #{x.call_method op, y}"

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;
}

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));
    }
}
Output:
5 + 3 = 8
5 - 3 = 2
5 * 3 = 15
5 / 3 = 1
5 % 3 = 2
5 to the power of 3 = 125

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;
}

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.

Clipper

procedure Test( a, b )
   ? "a+b", a + b
   ? "a-b", a - b
   ? "a*b", a * b
   // The quotient isn't integer, so we use the Int() function, which truncates it downward.
   ? "a/b", Int( a / b )
   // Remainder:
   ? "a%b", a % b
   // Exponentiation is also a base arithmetic operation
   ? "a**b", a ** b
   return

Clojure

(defn myfunc []
  (println "Enter x and y")
  (let [x (read), y (read)]
    (doseq [op '(+ - * / Math/pow rem)]
      (let [exp (list op x y)]
	(printf "%s=%s\n" exp (eval exp))))))
user=> (myfunc)
Enter x and y
3
6
(+ 3 6)=9
(- 3 6)=-3
(* 3 6)=18
(/ 3 6)=1/2
(Math/pow 3 6)=729.0
(rem 3 6)=3
nil

COBOL

       IDENTIFICATION DIVISION.
       PROGRAM-ID. Int-Arithmetic.

       DATA DIVISION.
       WORKING-STORAGE SECTION.

       01 A      PIC S9(10).
       01 B      PIC S9(10).
       01 Result PIC S9(10).

       PROCEDURE DIVISION.
           DISPLAY "First number: " WITH NO ADVANCING
           ACCEPT A
           DISPLAY "Second number: " WITH NO ADVANCING
           ACCEPT B
           
*          *> Note: The various ADD/SUBTRACT/etc. statements can be
*          *> replaced with COMPUTE statements, which allow those
*          *> operations to be defined similarly to other languages,
*          *> e.g. COMPUTE Result = A + B

           ADD A TO B GIVING Result
           DISPLAY "A + B = " Result

           SUBTRACT B FROM A GIVING Result
           DISPLAY "A - B = " Result

           MULTIPLY A BY B GIVING Result
           DISPLAY "A * B = " Result

*          *> Division here truncates towards zero. DIVIDE can take a
*          *> ROUNDED clause, which will round the result to the nearest
*          *> integer.
           DIVIDE A BY B GIVING Result
           DISPLAY "A / B = " Result

           COMPUTE Result = A ^ B
           DISPLAY "A ^ B = " Result
       
*          *> Matches sign of first argument.
           DISPLAY "A % B = " FUNCTION REM(A, B)

           GOBACK
           .

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.

Component Pascal

Works with Gardens Point Component Pascal

MODULE Arithmetic;
IMPORT CPmain,Console,RTS;

VAR
   x,y	  : INTEGER;
   arg	  : ARRAY 128 OF CHAR;
   status : BOOLEAN;
   

PROCEDURE Error(IN str : ARRAY OF CHAR);
BEGIN
   Console.WriteString(str);Console.WriteLn;
   HALT(1)
END Error;


BEGIN
   IF CPmain.ArgNumber() < 2 THEN Error("Give me two integers!") END;
   CPmain.GetArg(0,arg); RTS.StrToInt(arg,x,status);
   IF ~status THEN Error("Can't convert 	'"+arg+"' to Integer") END;
   CPmain.GetArg(1,arg); RTS.StrToInt(arg,y,status);
   IF ~status THEN Error("Can't convert '"+arg+"' to Integer") END;
   Console.WriteString("x + y >");Console.WriteInt(x + y,6);Console.WriteLn;
   Console.WriteString("x - y >");Console.WriteInt(x - y,6);Console.WriteLn;
   Console.WriteString("x * y >");Console.WriteInt(x * y,6);Console.WriteLn;
   Console.WriteString("x / y >");Console.WriteInt(x DIV y,6);Console.WriteLn;
   Console.WriteString("x MOD y >");Console.WriteInt(x MOD y,6);Console.WriteLn;
END Arithmetic.

command: cprun Arithmetic 12 23

Output:
x + y >    35
x - y >   -11
x * y >   276
x / y >     0
x MOD y >    12

Works with BlackBox Component Builder

MODULE Arithmetic;
IMPORT StdLog,DevCommanders,TextMappers;

PROCEDURE DoArithmetic(x,y: INTEGER);
BEGIN
        StdLog.String("x + y >");StdLog.Int(x + y);StdLog.Ln;
        StdLog.String("x - y >");StdLog.Int(x - y);StdLog.Ln;
        StdLog.String("x * y >");StdLog.Int(x * y);StdLog.Ln;
        StdLog.String("x / y >");StdLog.Int(x DIV y);StdLog.Ln;
        StdLog.String("x MOD y >");StdLog.Int(x MOD y);StdLog.Ln;
END DoArithmetic;

PROCEDURE Go*;
VAR
                params: DevCommanders.Par;
                s: TextMappers.Scanner;
                p : ARRAY 2 OF INTEGER;
                current: INTEGER;
BEGIN
        current := 0;
        params := DevCommanders.par;
        s.ConnectTo(params.text);
        s.SetPos(params.beg);
        s.Scan;
        WHILE(~s.rider.eot) DO
                IF (s.type = TextMappers.int) THEN
                        p[current] := s.int; INC(current);
                END;
                s.Scan;
        END;
        IF current = 2 THEN DoArithmetic(p[0],p[1]) END;
END Go;
END Arithmetic.

Command: Arithmetic.Go 12 23 ~

Output:
x + y > 35
x - y > -11
x * y > 276
x / y > 0
x MOD y > 12

Crystal

a = gets.not_nil!.to_i64
b = gets.not_nil!.to_i64

puts "Sum: #{a + b}"
puts "Difference: #{a - b}"
puts "Product: #{a * b}"
puts "Quotient (float division): #{a / b}"  # / always returns a float.
puts "Quotient (floor division): #{a // b}"
puts "Remainder: #{a % b}" # Sign of remainder matches that of the second operand (b).
puts "Power: #{a ** b}"    # Integers can only be raised to a positive exponent.

D

import std.stdio, std.string, std.conv;

void main() {
    int a = 10, b = 20;
    try {
        a = readln().strip().to!int();
        b = readln().strip().to!int();
    } catch (StdioException e) {}
    writeln("a = ", a, ", b = ", b);

    writeln("a + b = ", a + b);
    writeln("a - b = ", a - b);
    writeln("a * b = ", a * b);
    writeln("a / b = ", a / b);
    writeln("a % b = ", a % b);
    writeln("a ^^ b = ", a ^^ b);
}
Output:
a = -16, b = 5
a + b = -11
a - b = -21
a * b = -80
a / b = -3
a % b = -1
a ^^ b = -1048576

Shorter Version

Same output.

import std.stdio, std.string, std.conv, std.meta;

void main() {
    int a = -16, b = 5;
    try {
        a = readln().strip().to!int();
        b = readln().strip().to!int();
    } catch (StdioException e) {}
    writeln("a = ", a, ", b = ", b);

    foreach (op; AliasSeq!("+", "-", "*", "/", "%", "^^"))
        mixin(`writeln("a ` ~ op ~ ` b = ", a` ~ op ~ `b);`);
}

Division and modulus are defined as in C99.

Dart

import 'dart:io';
import 'dart:math' show pow;

void main() {
  print('enter a integer: ');
  int a = int.parse(stdin.readLineSync());
  print('enter another integer: ');
  int b = int.parse(stdin.readLineSync());

  print('a + b = ${a + b}');
  print('a - b = ${a - b}');
  print('a * b = ${a * b}');
  print('a / b = ${a ~/ b}');
  print('a % b = ${a % b}');
  print('a ^ b = ${pow(a, b)}');

  //Integer division uses the '~/' operator
}

dc

[Enter 2 integers on 1 line.
  Use whitespace to separate. Example: 2 3
  Use underscore for negative integers. Example: _10
]P ? sb sa
[add: ]P la lb + p sz
[sub: ]P la lb - p sz
[mul: ]P la lb * p sz
[div: ]P la lb / p sz  [truncates toward zero]sz
[mod: ]P la lb % p sz  [sign matches first operand]sz
[pow: ]P la lb ^ p sz

DCL

$ inquire a "Enter first number"
$ a = f$integer( a )
$ inquire b "Enter second number"
$ b = f$integer( b )
$ write sys$output "a + b = ", a + b
$ write sys$output "a - b = ", a - b
$ write sys$output "a * b = ", a * b
$ write sys$output "a / b = ", a / b  ! truncates down
Output:
$ @arithmetic_integer 
Enter first number: 2
Enter second number: 5
a + b = 7
a - b = -3
a * b = 10
a / b = 0
$ @arithmetic_integer 
Enter first number: -5
Enter second number: -2
a + b = -7
a - b = -3
a * b = 10
a / b = 2

Delphi

program IntegerArithmetic;

{$APPTYPE CONSOLE}

uses SysUtils, Math;

var
  a, b: Integer;
begin
  a := StrToInt(ParamStr(1));
  b := StrToInt(ParamStr(2));

  WriteLn(Format('%d + %d = %d', [a, b, a + b]));
  WriteLn(Format('%d - %d = %d', [a, b, a - b]));
  WriteLn(Format('%d * %d = %d', [a, b, a * b]));
  WriteLn(Format('%d / %d = %d', [a, b, a div b])); // rounds towards 0
  WriteLn(Format('%d %% %d = %d', [a, b, a mod b])); // matches sign of the first operand
  WriteLn(Format('%d ^ %d = %d', [a, b, Trunc(Power(a, b))]));
end.

DWScript

var a := StrToInt(ParamStr(0));
var b := StrToInt(ParamStr(1));

PrintLn(Format('%d + %d = %d', [a, b, a + b]));
PrintLn(Format('%d - %d = %d', [a, b, a - b]));
PrintLn(Format('%d * %d = %d', [a, b, a * b]));
PrintLn(Format('%d / %d = %d', [a, b, a div b])); 
PrintLn(Format('%d mod %d = %d', [a, b, a mod b])); 
PrintLn(Format('%d ^ %d = %d', [a, b, Trunc(Power(a, b))]));

Dyalect

Translation of: Swift

Dyalect has no operator for exponential.

let a = 6 
let b = 4
 
print("sum = \(a+b)")
print("difference = \(a-b)")
print("product = \(a*b)")
print("Integer quotient = \(a/b)")
print("Remainder = \(a%b)")

E

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

EasyLang

a = number input
b = number input
print a + b
print a - b
print a * b
print a div b
print a mod b
print pow a b

ECL

ArithmeticDemo(INTEGER A,INTEGER B) := FUNCTION
  ADDit       := A + B;
  SUBTRACTit  := A - B;
  MULTIPLYit  := A * B;
  INTDIVIDEit := A DIV B; //INTEGER DIVISION
  DIVIDEit    := A / B;   //standard division
  Remainder   := A % B;
  EXPit       := POWER(A,B);
  DS          := DATASET([{A,B,'A PLUS B is:',ADDit},
                          {A,B,'A MINUS B is:',SUBTRACTit},
			  {A,B,'A TIMES B is:',MULTIPLYit},
			  {A,B,'A INT DIVIDE BY B is:',INTDIVIDEit},
			  {A,B,'REMAINDER is:',Remainder},
			  {A,B,'A DIVIDE BY B is:',DIVIDEit},
			  {A,B,'A RAISED TO B:',EXPit}],
			  {INTEGER AVal,INTEGER BVal,STRING18 valuetype,STRING val});
										
  RETURN DS;
  END;
	
ArithmeticDemo(1,1);
ArithmeticDemo(2,2);
ArithmeticDemo(50,5);
ArithmeticDemo(10,3);
ArithmeticDemo(-1,2);
	
/* 	NOTE:Division by zero defaults to generating a zero result (0), 
   	rather than reporting a “divide by zero” error. 
   	This avoids invalid or unexpected data aborting a long job. 
   	This default behavior can be changed
*/

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])
}

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.

Elena

ELENA 6.x :

import system'math;
import extensions;

public program()
{
    var a := console.loadLineTo(new Integer());
    var b := console.loadLineTo(new Integer());
    
    console.printLine(a," + ",b," = ",a + b);
    console.printLine(a," - ",b," = ",a - b);
    console.printLine(a," * ",b," = ",a * b);
    console.printLine(a," / ",b," = ",a / b);   // truncates towards 0
    console.printLine(a," % ",b," = ",a.mod(b)); // matches sign of first operand
    console.printLine(a," ^ ",b," = ",a ^ b);
}

Elixir

Works with: Elixir version 1.4
defmodule Arithmetic_Integer do
  # Function to remove line breaks and convert string to int
  defp get_int(msg) do
    IO.gets(msg) |> String.strip |> String.to_integer
  end
  
  def task do
    # Get user input
    a = get_int("Enter your first integer: ") 
    b = get_int("Enter your second integer: ")
    
    IO.puts "Elixir Integer Arithmetic:\n"
    IO.puts "Sum:            #{a + b}"
    IO.puts "Difference:     #{a - b}"
    IO.puts "Product:        #{a * b}"
    IO.puts "True Division:  #{a / b}"                  # Float
    IO.puts "Division:       #{div(a,b)}"               # Truncated Towards 0
    IO.puts "Floor Division: #{Integer.floor_div(a,b)}" # floored integer division
    IO.puts "Remainder:      #{rem(a,b)}"               # Sign from first digit
    IO.puts "Modulo:         #{Integer.mod(a,b)}"       # modulo remainder (uses floored division)
    IO.puts "Exponent:       #{:math.pow(a,b)}"         # Float, using Erlang's :math
  end
end

Arithmetic_Integer.task
Output:
C:\Elixir>elixir Arithmetic_Integer.exs
Enter your first integer: 7
Enter your second integer: 3
Elixir Integer Arithmetic:

Sum:            10
Difference:     4
Product:        21
True Division:  2.3333333333333335
Division:       2
Floor Division: 2
Remainder:      1
Modulo:         1
Exponent:       343.0

C:\Elixir>elixir Arithmetic_Integer.exs
Enter your first integer: -7
Enter your second integer: 3
Elixir Integer Arithmetic:

Sum:            -4
Difference:     -10
Product:        -21
True Division:  -2.3333333333333335
Division:       -2
Floor Division: -3
Remainder:      -1
Modulo:         2
Exponent:       -343.0

C:\Elixir>elixir Arithmetic_Integer.exs
Enter your first integer: 7
Enter your second integer: -3
Elixir Integer Arithmetic:

Sum:            4
Difference:     10
Product:        -21
True Division:  -2.3333333333333335
Division:       -2
Floor Division: -3
Remainder:      1
Modulo:         -2
Exponent:       0.0029154518950437317

C:\Elixir>elixir Arithmetic_Integer.exs
Enter your first integer: -7
Enter your second integer: -3
Elixir Integer Arithmetic:

Sum:            -10
Difference:     -4
Product:        21
True Division:  2.3333333333333335
Division:       2
Floor Division: 2
Remainder:      -1
Modulo:         -1
Exponent:       -0.0029154518950437317

EMal

^|EMal has no divmod operator or built-in function,
 |its interface can be easily emulated as shown below.
 |The performace is worse than using / and % operators.
 |^
fun divmod = Pair by int dividend, int divisor
  Pair result = int%int().named("quotient", "remainder")
  result.quotient = dividend / divisor
  result.remainder = dividend % divisor
  return result
end
fun main = int by List args
  int a, b
  if args.length == 2
    a = int!args[0]
	b = int!args[1]
  else
    a = ask(int, "first number: ")
    b = ask(int, "second number: ")
  end
  writeLine("sum:              " + (a + b))
  writeLine("difference:       " + (a - b))
  writeLine("product:          " + (a * b))
  writeLine("integer quotient: " + (a / b)) # truncates towards 0
  writeLine("remainder:        " + (a % b)) # matches sign of first operand
  writeLine("exponentiation:   " + (a ** b))
  writeLine("logarithm:        " + (a // b))
  writeLine("divmod:           " + divmod(a, b))
  return 0
end
exit main(Runtime.args)
Output:
emal.exe Org\RosettaCode\AritmeticInteger.emal
first number: 19
second number: 7
sum:              26
difference:       12
product:          133
integer quotient: 2
remainder:        5
exponentiation:   893871739
logarithm:        2
divmod:           [2,5]

Emojicode

🏁🍇
  🍺🔢🆕🔡▶️👂🏼❗ 10❗️ ➡️ x 💭 Get first number
  🍺🔢🆕🔡▶️👂🏼❗ 10❗️ ➡️ y 💭 Get second number
  😀 🔤Sum: 🧲x➕y🧲🔤 ❗
  😀 🔤Difference: 🧲x➖y🧲🔤 ❗
  😀 🔤Product: 🧲x✖️y🧲🔤 ❗
  😀 🔤Quotient: 🧲x➗️y🧲🔤 ❗ 💭 Rounds towards 0
  😀 🔤Remainder: 🧲x🚮️y🧲🔤 ❗ 💭 Matches sign of first operand
🍉️

Erlang

% Implemented by Arjun Sunel
-module(arith).
-export([start/0]).
 
start() ->
   case io:fread("","~d~d") of
       {ok, [A,B]} ->
           io:format("Sum = ~w~n",[A+B]),
           io:format("Difference = ~w~n",[A-B]),
           io:format("Product = ~w~n",[A*B]),
           io:format("Quotient = ~w~n",[A div B]),      % truncates towards zero
           io:format("Remainder= ~w~n",[A rem B]),    % same sign as the first operand
           halt()
   end.

ERRE

PROGRAM INTEGER_ARITHMETIC

!
! for rosettacode.org
!

!$INTEGER

BEGIN
  INPUT("Enter a number ",A)
  INPUT("Enter another number ",B)

  PRINT("Addition ";A;"+";B;"=";(A+B))
  PRINT("Subtraction ";A;"-";B;"=";(A-B))
  PRINT("Multiplication ";A;"*";B;"=";(A*B))
  PRINT("Integer division ";A;"div";B;"=";(A DIV B))
  PRINT("Remainder or modulo ";A;"mod";B;"=";(A MOD B))
  PRINT("Power ";A;"^";B;"=";(A^B))
END PROGRAM
Output:
Enter a number ? 12
Enter another number ? 5
Addition  12 + 5 = 17
Subtraction  12 - 5 = 7
Multiplication  12 * 5 = 60
Integer division  12 div 5 = 2
Remainder or modulo  12 mod 5 = 2
Power  12 ^ 5 = 248832

Truncate towards: 0

Remainder sign matches: first operand

In C-64 ERRE version you must use INT(A/B) for division and A-B*INT(A/B) for modulus.

Euphoria

include get.e

integer a,b

a = floor(prompt_number("a = ",{}))
b = floor(prompt_number("b = ",{}))

printf(1,"a + b = %d\n", a+b)
printf(1,"a - b = %d\n", a-b)
printf(1,"a * b = %d\n", a*b)
printf(1,"a / b = %g\n", a/b) -- does not truncate
printf(1,"remainder(a,b) = %d\n", remainder(a,b)) -- same sign as first operand
printf(1,"power(a,b) = %g\n", power(a,b))
Output:
a = 2
b = 3
a + b = 5
a - b = -1
a * b = 6
a / b = 0.666667
remainder(a,b) = 2
power(a,b) = 8

Excel

If the numbers are typed into cells A1 and B1

For sum, type in C1

=$A1+$B1

For difference, type in D1

=$A1-$B1

For product, type in E1

=$A1*$B1

For quotient, type in F1

=QUOTIENT($A1,$B1)

For remainder, type in G1

=MOD($A1,$B1)

For exponentiation, type in H1

=$A1^$B1

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

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.

FALSE

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

Fermat

Integer division rounds towards zero; remainders are always positive regardless of the signs of the numbers.

?a;
?b;
!!('Sum:              a+b=',a+b);
!!('Difference:       a-b=',a-b);
!!('Product:          a*b=',a*b);
!!('Integer quotient: a\b=',a\b);
!!('Remainder:        a|b=',a|b);
!!('Exponentiation:   a^b=',a^b);
Output:

>a := 64 >b := -5 Sum: a+b= 59 Difference: a-b= 69 Product: a*b= -320 Integer quotient: a\b= -12 Remainder: a|b= 4 Exponentiation: a^b= 1 / 1073741824

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 )

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

FreeBASIC

' FB 1.05.0 Win64

Dim As Integer i, j
Input "Enter two integers separated by a comma"; i, j
Print i;" + "; j; " = "; i + j
Print i;" - "; j; " = "; i - j
Print i;" * "; j; " = "; i * j
Print i;" / "; j; " = "; i \ j
Print i;" % "; j; " = "; i Mod j 
Print i;" ^ "; j; " = "; i ^ j
Sleep

' Integer division (for which FB uses the '\' operator) rounds towards zero

' Remainder (for which FB uses the Mod operator) will, if non-zero, match the sign
' of the first operand

Sample input and output:-

Output:
Enter two integers separated by a comma? -12, 7
-12 +  7 = -5
-12 -  7 = -19
-12 *  7 = -84
-12 /  7 = -1
-12 %  7 = -5
-12 ^  7 = -35831808

friendly interactive shell

read a
read b
echo 'a + b =' (math "$a + $b") # Sum
echo 'a - b =' (math "$a - $b") # Difference
echo 'a * b =' (math "$a * $b") # Product
echo 'a / b =' (math "$a / $b") # Integer quotient
echo 'a % b =' (math "$a % $b") # Remainder
echo 'a ^ b =' (math "$a ^ $b") # Exponentation

Frink

This demonstrates normal division (which produces rational numbers when possible), div, and mod. div rounds toward negative infinity (defined as floor[x/y]). mod uses the sign of the second number (defined as x - y * floor[x/y]). All operators automatically produce big integers or exact rational numbers when necessary.

[a,b] = input["Enter numbers",["a","b"]]
ops=["+", "-", "*", "/", "div" ,"mod" ,"^"]
for op = ops
{
   str = "$a $op $b"
   println["$str = " + eval[str]]
}
Output:
10 + 20 = 30
10 - 20 = -10
10 * 20 = 200
10 / 20 = 1/2 (exactly 0.5)
10 div 20 = 0
10 mod 20 = 10
10 ^ 20 = 100000000000000000000

FutureBasic

Basic program

window 1, @"Integer Arithmetic", ( 0, 0, 400, 300 )

NSInteger a = 25
NSInteger b = 53

print "addition        "a" + "b" = " (a + b)
print "subtraction     "a" - "b" = " (a - b)
print "multiplication  "a" * "b" = " (a * b)
print "division        "a" / "b" = " (a / b)
printf @"float division  %ld / %ld = %f", a, b, (float)a / (float)b
print "modulo          "a" % "b" = " (a mod b)
print "power           "a" ^ "b" = " (a ^ b)

HandleEvents

Output:

addition:       25 + 53 = 78
subtraction:    25 - 53 = -28
multiplication: 25 * 53 = 1325
division:       25 / 53 = 0
float division: 25 / 53 = 0.471698
modulo:         25 mod 53 = 25
power:          25 ^ 53 = 1.232595e+74

Standalone Intel, M1, M2 Macintosh application with user input

_window = 1
begin enum 1
_int1Label
_int1Field
_int2Label
_int2Field
_calcResults
_calcBtn
end enum

void local fn BuildWindow
CGRect r

r = fn CGRectMake( 0, 0, 480, 360 )
window _window, @"Integer Arithmetic", r, NSWindowStyleMaskTitled + NSWindowStyleMaskClosable + NSWindowStyleMaskMiniaturizable

r = fn CGRectMake( 240, 320, 150, 24 )
textlabel _int1Label, @"Enter first integer:", r, _window
ControlSetAlignment( _int1Label, NSTextAlignmentRight )
r = fn CGRectMake( 400, 322, 60, 24 )
textfield _int1Field, YES, @"25", r, _window
ControlSetAlignment( _int1Field, NSTextAlignmentCenter )
ControlSetUsesSingleLineMode( _int1Field, YES )
ControlSetFormat( _int1Field, @"0123456789-", YES, 5, NULL )

r = fn CGRectMake( 240, 290, 150, 24 )
textlabel _int2Label, @"Enter second integer:", r, _window
ControlSetAlignment( _int2Label, NSTextAlignmentRight )
r = fn CGRectMake( 400, 292, 60, 24 )
textfield _int2Field, YES, @"53", r, _window
ControlSetAlignment( _int2Field, NSTextAlignmentCenter )
ControlSetUsesSingleLineMode( _int2Field, YES )
ControlSetFormat( _int2Field, @"0123456789-", YES, 5, NULL )

r = fn CGRectMake( 50, 60, 380, 200 )
textview _calcResults, r,,, _window
TextViewSetTextContainerInset( _calcResults, fn CGSizeMake( 10, 20 ) )
TextSetFontWithName( _calcResults, @"Menlo", 13.0 )
TextViewSetEditable( _calcResults, NO )

r = fn CGRectMake( 370, 13, 100, 32 )
button _calcBtn,,, @"Calculate", r
end fn

local fn PerformCalculations
CFStringRef tempStr

NSInteger i1 = fn ControlIntegerValue( _int1Field )
NSInteger i2 = fn ControlIntegerValue( _int2Field )

CFMutableStringRef mutStr = fn MutableStringWithCapacity( 0 )

// Display inout integers
tempStr = fn StringWithFormat( @"Number 1: %ld\nNumber 2: %ld\n\n", i1, i2 )
MutableStringAppendString( mutStr, tempStr )

// Add
tempStr = fn StringWithFormat( @"Addition: %ld + %ld = %ld\n", i1, i2, i1 + i2 )
MutableStringAppendString( mutStr, tempStr )

// Subtract
tempStr = fn StringWithFormat( @"Subtraction: %ld - %ld = %ld\n", i1, i2, i1 - i2 )
MutableStringAppendString( mutStr, tempStr )

// Multiply
tempStr = fn StringWithFormat( @"Multiplication: %ld * %ld = %ld\n", i1, i2, i1 * i2 )
MutableStringAppendString( mutStr, tempStr )

if ( i2 != 0 )

// Divide
tempStr = fn StringWithFormat( @"Integer Division: %ld / %ld = %ld\n", i1, i2, i1 / i2 )
MutableStringAppendString( mutStr, tempStr )

// Float Divide
tempStr = fn StringWithFormat( @"Float Division: %ld / %ld = %f\n", i1, i2, (float)i1 / (float)i2 )
MutableStringAppendString( mutStr, tempStr )

// mod
tempStr = fn StringWithFormat( @"Modulo: %ld mod %ld = %ld remainder\n", i1, i2, i1 mod i2 )
MutableStringAppendString( mutStr, tempStr )

// power
tempStr = fn StringWithFormat( @"Power: %ld ^ %ld = %e\n", i1, i2, i1 ^ i2 )
MutableStringAppendString( mutStr, tempStr )

else

MutableStringAppendString( mutStr, @"Cannot divide by zero." )

end if

TextSetString( _calcResults, mutStr )
end fn

void local fn DoDialog( ev as long, tag as long, wnd as long )
'~'1
select ( ev )
case _btnClick
select ( tag )
case _calcBtn : fn PerformCalculations
end select
case _windowWillClose : end
end select
end fn

on dialog fn DoDialog

fn BuildWindow

HandleEvents

Output:

Number 1: 25
Number 2: 53

Addition: 25 + 53 = 78
Subtraction: 25 - 53 = -28
Multiplication: 25 * 53 = 1325
Integer Division: 25 / 53 = 0
Float Division: 25 / 53 = 0.471698
Modulo: 25 mod 53 = 25 remainder
Power: 25 ^ 53 = 1.232595e+74

Gambas

Public Sub Main()
  Dim a, b As String
  Dim c, d As Integer

  Print "Enter two integer numbers, separated by space:"
  Input a, b

  c = CInt(a)
  d = CInt(b)

  Print "Sum: " & (c + d)
  Print "Difference:" & (c - d)
  Print "Product: " & (c * d)
  Print "Integer: " & (c Div d)
  Print "Remainder: " & (c Mod d)
  Print "Exponentiation: " & (c ^ d)

End

Output:

Enter two integer numbers, separated by space:
8 1
Sum: 9
Difference:7
Product: 8
Integer: 8
Remainder: 0
Exponentiation: 8

GAP

run := function()
  local a, b, f;
  f := InputTextUser();
  Print("a =\n");
  a := Int(Chomp(ReadLine(f)));
  Print("b =\n");
  b := Int(Chomp(ReadLine(f)));
  Display(Concatenation(String(a), " + ", String(b), " = ", String(a + b)));
  Display(Concatenation(String(a), " - ", String(b), " = ", String(a - b)));
  Display(Concatenation(String(a), " * ", String(b), " = ", String(a * b)));
  Display(Concatenation(String(a), " / ", String(b), " = ", String(QuoInt(a, b)))); # toward 0
  Display(Concatenation(String(a), " mod ", String(b), " = ", String(RemInt(a, b)))); # nonnegative
  Display(Concatenation(String(a), " ^ ", String(b), " = ", String(a ^ b)));
  CloseStream(f);
end;

GDScript

Requires Godot 4.

@tool
extends Node

@export var a: int:
	set(value):
		a = value
		refresh()

@export var b: int:
	set(value):
		b = value
		refresh()

# Output properties
@export var sum: int
@export var difference: int
@export var product: int
@export var integer_quotient: int
@export var remainder: int
@export var exponentiation: int
@export var divmod: int

func refresh():
	sum = a + b
	difference = a - b
	product = a * b
	integer_quotient = a / b # Rounds towards 0
	remainder = a % b # Matches the sign of a
	exponentiation = pow(a, b)

Genie

Note: Using init:int and the return from the init block was introduced in release 0.43.92, February 2019.

[indent=4]
/*
   Arithmethic/Integer, in Genie
   valac arithmethic-integer.gs
*/

init:int
    a:int = 0
    b:int = 0
    if args.length > 2 do b = int.parse(args[2])
    if args.length > 1 do a = int.parse(args[1])

    print @"a+b: $a plus  $b is $(a+b)"
    print @"a-b: $a minus $b is $(a-b)"
    print @"a*b: $a times $b is $(a*b)"
    print @"a/b: $a by    $b quotient is  $(a/b)  (rounded mode is TRUNCATION)"
    print @"a%b: $a by    $b remainder is $(a%b)  (sign matches first operand)"

    print "\nGenie does not include a raise to power operator"

    return 0
Output:
prompt$ valac arithmetic-integer.gs
prompt$ ./arithmetic-integer -390 100
a+b: -390 plus  100 is -290
a-b: -390 minus 100 is -490
a*b: -390 times 100 is -39000
a/b: -390 by    100 quotient is  -3  (rounded mode is TRUNCATION)
a%b: -390 by    100 remainder is -90  (sign matches first operand)

Genie does not include a raise to power operator

GEORGE

R (m) ;
R (n) ;
m n + P;
m n - P;
m n × P;
m n div P;
m n rem P;

Go

int

package main

import "fmt"

func main() {
    var a, b int
    fmt.Print("enter two integers: ")
    fmt.Scanln(&a, &b)
    fmt.Printf("%d + %d = %d\n", a, b, a+b)
    fmt.Printf("%d - %d = %d\n", a, b, a-b)
    fmt.Printf("%d * %d = %d\n", a, b, a*b)
    fmt.Printf("%d / %d = %d\n", a, b, a/b)  // truncates towards 0
    fmt.Printf("%d %% %d = %d\n", a, b, a%b) // same sign as first operand
    // no exponentiation operator
}
Example run:
enter two integers: -5 3
-5 + 3 = -2
-5 - 3 = -8
-5 * 3 = -15
-5 / 3 = -1
-5 % 3 = -2

big.Int

package main

import (
    "fmt"
    "math/big"
)

func main() {
    var a, b, c big.Int
    fmt.Print("enter two integers: ")
    fmt.Scan(&a, &b)
    fmt.Printf("%d + %d = %d\n", &a, &b, c.Add(&a, &b))
    fmt.Printf("%d - %d = %d\n", &a, &b, c.Sub(&a, &b))
    fmt.Printf("%d * %d = %d\n", &a, &b, c.Mul(&a, &b))

    // Quo, Rem functions work like Go operators on int:
    // quo truncates toward 0,
    // and a non-zero rem has the same sign as the first operand.
    fmt.Printf("%d quo %d = %d\n", &a, &b, c.Quo(&a, &b))
    fmt.Printf("%d rem %d = %d\n", &a, &b, c.Rem(&a, &b))

    // Div, Mod functions do Euclidean division:
    // the result m = a mod b is always non-negative,
    // and for d = a div b, the results d and m give d*y + m = x.
    fmt.Printf("%d div %d = %d\n", &a, &b, c.Div(&a, &b))
    fmt.Printf("%d mod %d = %d\n", &a, &b, c.Mod(&a, &b))

    // as with int, no exponentiation operator
}
Example run:
enter two integers: -5 3
-5 + 3 = -2
-5 - 3 = -8
-5 * 3 = -15
-5 quo 3 = -1
-5 rem 3 = -2
-5 div 3 = -2
-5 mod 3 = 1

Golfscript

Quotients round towards negative infinity. Remainders match the sign of the second operand.

n/~~:b;~:a;a b+n a b-n a b*n a b/n a b%n a b?

Groovy

Solution:

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}   !!! Converts to floating point!
(int)(a / b) = (int)(${a} / ${b}) = ${(int)(a / b)}              !!! Truncates downward after the fact
 a.intdiv(b) =  ${a}.intdiv(${b}) = ${a.intdiv(b)}              !!! Behaves as if truncating downward, actual implementation varies
       a % b =        ${a} % ${b} = ${a % b}

Exponentiation is also a base arithmetic operation in Groovy, so:
      a ** b =       ${a} ** ${b} = ${a ** b}
"""
}

Test:

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   !!! Converts to floating point!
(int)(a / b) = (int)(5 / 3) = 1              !!! Truncates downward after the fact
 a.intdiv(b) =  5.intdiv(3) = 1              !!! Behaves as if truncating downward, actual implementation varies
       a % b =        5 % 3 = 2

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

Harbour

procedure Test( a, b )
   ? "a+b", a + b
   ? "a-b", a - b
   ? "a*b", a * b
   // The quotient isn't integer, so we use the Int() function, which truncates it downward.
   ? "a/b", Int( a / b )
   // Remainder:
   ? "a%b", a % b
   // Exponentiation is also a base arithmetic operation
   ? "a**b", a ** b
   return

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)

Haxe

class BasicIntegerArithmetic {
    public static function main() {
        var args =Sys.args();
        if (args.length < 2) return;
        var a = Std.parseFloat(args[0]);
        var b = Std.parseFloat(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));
    }
}

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

HolyC

I64 *a, *b;
a = Str2I64(GetStr("Enter your first number: "));
b = Str2I64(GetStr("Enter your second number: "));

if (b == 0)
  Print("Error: The second number must not be zero.\n");
else {
  Print("a + b = %d\n", a + b);
  Print("a - b = %d\n", a - b);
  Print("a * b = %d\n", a * b);
  Print("a / b = %d\n", a / b); /* rounds down */
  Print("a % b = %d\n", a % b); /* same sign as first operand */
  Print("a ` b = %d\n", a ` b);
}

i

main
	a $= integer(in(' ')); ignore
	b $= integer(in('\n')); ignore
	
	print("Sum:"		, a + b)
	print("Difference:", a - b)
	print("Product:"	, a * b)
	print("Quotient:"	, a / b) // rounds towards zero
	print("Modulus:"	, a % b) // same sign as first operand
	print("Exponent:"	, a ^ b)
}

Icon and Unicon

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

Inform 7

Enter Two Numbers is a room.

Numerically entering is an action applying to one number. Understand "[number]" as numerically entering.

The first number is a number that varies.

After numerically entering for the first time:
	now the first number is the number understood.

After numerically entering for the second time:
	let A be the first number;
	let B be the number understood;
	say "[A] + [B] = [A + B]."; [operator syntax]
	say "[A] - [B] = [A minus B]."; [English syntax]
	let P be given by P = A * B where P is a number; [inline equation]
	say "[A] * [B] = [P].";
	let Q be given by the Division Formula; [named equation]
	say "[A] / [B] = [Q].";
	say "[A] mod [B] = [remainder after dividing A by B].";
	end the story.

Equation - Division Formula
	Q = A / B
where Q is a number, A is a number, and B is a number.

This solution shows four syntaxes: mathematical operators, English operators, inline equations, and named equations. Division rounds toward zero, and the remainder has the same sign as the quotient.

J

calc =:    + , - , * , <.@% , |~ , ^

The function calc constructs a list of numeric results for this task. The implementation of integer division we use here (<.@%.) rounds down (towards negative infinity), and this is compatible with the remainder implementation we use here.

   17 calc 3
20 14 51 5 2 4913

The function bia assembles these results, textually:

labels  =: ];.2 'Sum: Difference: Product: Quotient: Remainder: Exponentiation: '
combine =: ,. ":@,.
bia     =: labels combine calc

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

Java

import java.util.Scanner;

public class IntegerArithmetic {
    public static void main(String[] args) {
        // Get the 2 numbers from command line arguments
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();

        int sum = a + b;        // The result of adding 'a' and 'b' (Note: integer addition is discouraged in print statements due to confusion with string concatenation)
        int difference = a - b; // The result of subtracting 'b' from 'a'
        int product = a * b;    // The result of multiplying 'a' and 'b'
        int division = a / b;   // The result of dividing 'a' by 'b' (Note: 'division' does not contain the fractional result)
        int remainder = a % b;  // The remainder of dividing 'a' by 'b'

        System.out.println("a + b = " + sum);
        System.out.println("a - b = " + difference);
        System.out.println("a * b = " + product);
        System.out.println("quotient of a / b = " + division);   // truncates towards 0
        System.out.println("remainder of a / b = " + remainder);   // same sign as first operand
    }
}

JavaScript

WScript

Works with: JScript
Works with: SpiderMonkey

Note that the operators work the same in all versions of JavaScript; the requirement for specific implementations is in order to get user input.

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 | 0)); // "| 0" casts it to an integer
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
remainder: a % b = -21

Node.JS

// Invoked as node script_name.js <a> <b>. Positions 0 and 1 in the argv array contain 'node' and 'script_name.js' respectively
var a = parseInt(process.argv[2], 10);
var b = parseInt(process.argv[3], 10);

var sum = a + b;
var difference = a - b;
var product = a * b;
var division = a / b;
var remainder = a % b;  // This produces the remainder after dividing 'b' into 'a'. The '%' operator is called the 'modulo' operator

console.log('a + b = %d', sum);  // The %d syntax is a placeholder that is replaced by the sum
console.log('a - b = %d', difference);
console.log('a * b = %d', product);
console.log('a / b = %d', division);
console.log('a % b = %d', remainder);
Output:
$ node arith.js 10 7
a + b = 17
a - b = 3
a * b = 70
a / b = 1.4285714285714286
a % b = 3

jq

# Lines which do not have two integers are skipped:

def arithmetic:
  split(" ") | select(length > 0) | map(tonumber)
  | if length > 1 then
    .[0] as $a | .[1] as $b
    | "For a = \($a) and b = \($b):\n" +
      "a + b = \($a + $b)\n" +
      "a - b = \($a - $b)\n" +
      "a * b = \($a * $b)\n" +
      "a/b|floor = \($a / $b | floor)\n" +
      "a % b = \($a % $b)\n" +
      "a | exp = \($a | exp)\n"
    else empty
    end ;

arithmetic
Output:
$ jq -R -r -f arithmetic.jq
7 -2
For a = 7 and b = -2:
a + b = 5
a - b = 9
a * b = -14
a/b|floor = -4
a % b = 1
a | exp = 1096.6331584284585

2 -7
For a = 2 and b = -7:
a + b = -5
a - b = 9
a * b = -14
a/b|floor = -1
a % b = 2
a | exp = 7.38905609893065

-2 -7
For a = -2 and b = -7:
a + b = -9
a - b = 5
a * b = 14
a/b|floor = 0
a % b = -2
a | exp = 0.1353352832366127

Jsish

"use strict";
/* Arthimetic/Integer, in Jsish */
var line = console.input();
var nums = line.match(/^\s*([+-]?[0-9]+)\s+([+-]?[0-9]+)\s*/);
var a = Number(nums[1]);
var b = Number(nums[2]);

puts("A is ", a, ", B is ", b);
puts("Sum               A + B is ", a + b);
puts("Difference        A - B is ", a - b);
puts("Product           A * B is ", a * b);
puts("Integer quotient  A / B is ", a / b | 0, " truncates toward 0");
puts("Remainder         A % B is ", a % b, " sign follows first operand");
puts("Exponentiation    A to the power B is ", Math.pow(a, b));

/*
=!INPUTSTART!=
7 4
=!INPUTEND!=
*/


/*
=!EXPECTSTART!=
A is  7 , B is  4
Sum               A + B is  11
Difference        A - B is  3
Product           A * B is  28
Integer quotient  A / B is  1  truncates toward 0
Remainder         A % B is  3  sign follows first operand
Exponentiation    A to the power B is  2401
=!EXPECTEND!=
*/
Output:
prompt$ jsish -u arithmeticInteger.jsi
[PASS] arithmeticInteger.jsi

Julia

function arithmetic (a = parse(Int, readline()), b = parse(Int, readline()))
  for op in  [+,-,*,div,rem]
    println("a $op b = $(op(a,b))")
  end
end
Output:
julia> arithmetic()
4
5
a + b = 9
a - b = -1
a * b = 20
a div b = 0
a rem b = 4

Kotlin

import kotlin.math.pow // not an operator but in the standard library

fun main() {
    val r = Regex("""-?[0-9]+\s+-?[0-9]+""")
    print("Enter two integers separated by space(s): ")
    val input: String = readLine()!!.trim()
    val index = input.lastIndexOf(' ')
    val a = input.substring(0, index).trimEnd().toLong()
    val b = input.substring(index + 1).toLong()
    println("$a + $b = ${a + b}")
    println("$a - $b = ${a - b}")
    println("$a * $b = ${a * b}")
    println("$a / $b = ${a / b}")  // rounds towards zero
    println("$a % $b = ${a % b}")  // if non-zero, matches sign of first operand
    println("$a ^ $b = ${a.toDouble().pow(b.toDouble())}")
}
}
Output:
Enter two integers separated by space(s): 2 63
2 + 63 = 65
2 - 63 = -61
2 * 63 = 126
2 / 63 = 0
2 % 63 = 2
2 ^ 63 = 9.223372036854776E18

LabVIEW

This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.

Lambdatalk

Translation of Racket

{def arithmetic 
 {lambda {:x :y}
  {S.map {{lambda {:x :y :op} 
                  {br}applying :op on :x & :y returns {:op :x :y}} :x :y}
         + - * / % pow max min = > <}}}
-> arithmetic

{arithmetic 8 12}
-> 
applying + on 8 & 12 returns 20 
applying - on 8 & 12 returns -4 
applying * on 8 & 12 returns 96 
applying / on 8 & 12 returns 0.6666666666666666 
applying % on 8 & 12 returns 8 
applying pow on 8 & 12 returns 68719476736 
applying max on 8 & 12 returns 12 
applying min on 8 & 12 returns 8 
applying = on 8 & 12 returns false 
applying > on 8 & 12 returns false 
applying < on 8 & 12 returns true

Lasso

local(a = 6, b = 4)
#a + #b // 10
#a - #b // 2
#a * #b // 24
#a / #b // 1
#a % #b // 2
math_pow(#a,#b) // 1296
math_pow(#b,#a) // 4096

LDPL

data:
x is number
y is number
result is number

procedure:
display "Enter x: "
accept x
display "Enter y: "
accept y
add x and y in result
display "x + y = " result lf
subtract y from x in result
display "x - y = " result lf
multiply x by y in result
display "x * y = " result lf
divide x by y in result       # There is no integer division but
floor result                  # floor rounds toward negative infinity
display "x / y = " result lf
modulo x by y in result
display "x % y = " result lf  # Returns the sign of the 2nd argument
raise x to y in result
display "x ^ y = " result lf
Output:
Enter x: 13
Enter y: 4
x + y = 17
x - y = 9
x * y = 52
x / y = 3
x % y = 1
x ^ y = 28561

LFE

(defmodule arith
  (export all))

(defun demo-arith ()
  (case (: io fread '"Please enter two integers: " '"~d~d")
    ((tuple 'ok (a b))
      (: io format '"~p + ~p = ~p~n" (list a b (+ a b)))
      (: io format '"~p - ~p = ~p~n" (list a b (- a b)))
      (: io format '"~p * ~p = ~p~n" (list a b (* a b)))
      (: io format '"~p^~p = ~p~n" (list a b (: math pow a b)))
      ; div truncates towards zero
      (: io format '"~p div ~p = ~p~n" (list a b (div a b)))
      ; rem's result takes the same sign as the first operand
      (: io format '"~p rem ~p = ~p~n" (list a b (rem a b))))))

Usage from the LFE REPL:

> (slurp '"arith.lfe")
#(ok arith)
> (demo-arith)
Please enter two integers: 2 8
2 + 8 = 10
2 - 8 = -6
2 * 8 = 16
2^8 = 256.0
2 div 8 = 0
2 rem 8 = 2
ok

Liberty BASIC

Note that raising to a power can display very large integers without going to approximate power-of-ten notation.

input "Enter the first integer:  "; first
input "Enter the second integer: "; second

print "The sum is " ; first + second
print "The difference is " ; first -second
print "The product is " ; first *second
if second <>0 then print "The integer quotient is " ; int( first /second); " (rounds towards 0)" else print "Division by zero not allowed."
print "The remainder is " ; first MOD second; " (sign matches first operand)"
print "The first raised to the power of the second is " ; first ^second

LIL

# Arithmetic/Integer, in LIL
write "Enter two numbers separated by space: "
if {[canread]} {set line [readline]}
print

set a [index $line 0]
set b [index $line 1]
print "A is $a"", B is $b"
print "Sum               A + B is [expr $a + $b]"
print "Difference        A - B is [expr $a - $b]"
print "Product           A * B is [expr $a * $b]"
print "Integer Quotient  A \\ B is [expr $a \ $b], truncates toward zero"
print "Remainder         A % B is [expr $a % $b], sign follows first operand"
print "LIL has no exponentiation expression operator"
Output:
prompt$ echo '7 4' | lil arithmeticInteger.lil  
Enter two numbers separated by space: 
A is 7, B is 4
Sum               A + B is 11
Difference        A - B is 3
Product           A * B is 28
Integer Quotient  A \ B is 1, truncates toward zero
Remainder         A % B is 3, sign follows first operand
LIL has no exponentiation expression operator

prompt$ echo '-7 4' | lil arithmeticInteger.lil
Enter two numbers separated by space:
A is -7, B is 4
Sum               A + B is -3
Difference        A - B is -11
Product           A * B is -28
Integer Quotient  A \ B is -1, truncates toward zero
Remainder         A % B is -3, sign follows first operand
LIL has no exponentiation expression operator

Lingo

-- X, Y: 2 editable field members, shown as sprites in the current GUI
x = integer(member("X").text)
y = integer(member("Y").text)

put "Sum: "       , x + y
put "Difference: ", x - y
put "Product: "   , x * y
put "Quotient: "  , x / y   -- Truncated towards zero
put "Remainder: " , x mod y -- Result has sign of left operand
put "Exponent: "  , power(x, y)

Little

# Maybe you need to import the mathematical funcions 
# from Tcl with:
# eval("namespace path ::tcl::mathfunc");

void main() {
    int a, b; 
    puts("Enter two integers:");
    a = (int)(gets(stdin)); 
    b = (int)(gets(stdin)); 
    puts("${a} + ${b} = ${a+b}");
    puts("${a} - ${b} = ${a-b}");
    puts("${a} * ${b} = ${a*b}");
    puts("${a} / ${b} = ${a/b}, remainder ${a%b}");
    puts("${a} to the power of ${b} = ${(int)pow(a,b)}");
}

LiveCode

ask "enter 2 numbers (comma separated)"
if it is not empty then
    put item 1 of it into n1
    put item 2 of it into n2
    put sum(n1,n2) into ai["sum"]
    put n1 * n2 into ai["product"]
    put n1 div n2 into ai["quotient"]  -- truncates
    put n1 mod n2 into ai["remainder"]
    put n1^n2 into ai["power"]
    combine ai using comma and colon
    put ai
end if

Examples

-2,4  - power:16,product:-8,quotient:0,remainder:-2,sum:2
2,-4  - power:0.0625,product:-8,quotient:0,remainder:2,sum:-2
-2,-4 - power:0.0625,product:8,quotient:0,remainder:-2,sum:-6
2,4   - power:16,product:8,quotient:0,remainder:2,sum:6
11,4  - power:14641,product:44,quotient:2,remainder:3,sum:15

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.

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

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))

M2000 Interpreter

We can use variables with %, which are double inside with no decimal part. These can have 17 digits. Also A%=1.5 make it 2, not 1. This has a tricky situation: A%=1/2 give 1 to A%. We can use FLOOR() or INT() is the same, or CEIL(), and there is a BANK() which is a Banker Round: BANK(2.5)=2 and BANK(3.5)=4.



MODULE LikeCommodoreBasic {
      \\ ADDITION: EUCLIDEAN DIV# & MOD# AND ** FOR POWER INCLUDING ^
      10 INPUT "ENTER A NUMBER:"; A%
      20 INPUT "ENTER ANOTHER NUMBER:"; B%
      30 PRINT "ADDITION:";A%;"+";B%;"=";A%+B%
      40 PRINT "SUBTRACTION:";A%;"-";B%;"=";A%-B%
      50 PRINT "MULTIPLICATION:";A%;"*";B%;"=";A%*B%
      60 PRINT "INTEGER DIVISION:";A%;"DIV";B%;"=";A% DIV B%
      65 PRINT "INTEGER EUCLIDEAN DIVISION:";A%;"DIV";B%;"=";A% DIV# B%
      70 PRINT "REMAINDER OR MODULO:";A%;"MOD";B%;"=";A% MOD B%
      75 PRINT "EUCLIDEAN REMAINDER OR MODULO:";A%;"MOD#";B%;"=";A% MOD# B%
      80 PRINT "POWER:";A%;"^";B%;"=";A%^B%
      90 PRINT "POWER:";A%;"**";B%;"=";A%**B%
}
LikeCommodoreBasic


Module IntegerTypes {
      a=12% ' Integer 16 bit
      b=12& ' Long 32 bit
      c=12@' Decimal (29 digits)
      Def ExpType$(x)=Type$(x)
      Print ExpType$(a+1)="Double"
      Print ExpType$(a+1%)="Integer"
      Print ExpType$(a div 5)="Double"
      Print ExpType$(a div 5%)="Double"
      Print ExpType$(a mod 5)="Double"
      Print ExpType$(a mod 5%)="Double"
      Print ExpType$(a**2)="Double"
      
      Print ExpType$(b+1)="Double"
      Print ExpType$(b+1&)="Long"
      Print ExpType$(b div 5)="Double"
      Print ExpType$(b div 5&)="Double"
      Print ExpType$(b mod 5)="Double"
      Print ExpType$(b mod 5&)="Double"
      Print ExpType$(b**2)="Double"

      Print ExpType$(c+1)="Decimal"
      Print ExpType$(c+1@)="Decimal"
      Print ExpType$(c div 5)="Decimal"
      Print ExpType$(c div 5@)="Decimal"
      Print ExpType$(c mod 5)="Decimal"
      Print ExpType$(c mod 5@)="Decimal"     
      Print ExpType$(c**2)="Double"
}
IntegerTypes

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')

Maple

These operations are all built-in. As all operations are exact, there are no rounding issues involved.

DoIt := proc()
        local a := readstat( "Input an integer: " ):
        local b := readstat( "Input another integer: " ):
        printf( "Sum = %d\n",  a + b ):
        printf( "Difference = %d\n",  a - b ):
        printf( "Product = %d\n",  a * b ):
        printf( "Quotient = %d\n",  iquo( a, b, 'c' ) ):
        printf( "Remainder = %d\n", c ); # or irem( a, b )
        NULL # quiet return
end proc:

Here is an example of calling DoIt.

> DoIt();
Input an integer: 15;
Input another integer: 12;
Sum = 27
Difference = 3
Product = 180
Quotient = 1
Remainder = 3
>

Mathematica/Wolfram Language

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: ", Quotient[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

Mathcad

The text below (from "Task Notes" onwards) is pretty well what you will see on a Mathcad worksheet across most versions (eg, Mathcad 15, Mathcad Prime 6.0, and Mathcad Prime 6.0 Express). Mathcad's "whiteboard" interface allows the user to mix formatted text regions with formatted math regions. Text region formatting is fairly arbitrary, individual characters can have their font, font size and bold/italic/underline settings set or changed at will. Math regions use amendable styles to identify variables, functions (normally built-in functions), keywords, system words and units (Mathcad has a units-aware, SI-based quantity system). It really is a simple as 'writing' on the whiteboard.


Task Notes

For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).

There is no quotient function in Mathcad, only complex division. We emulate quotient by standard division followed by rounding using both floor, which rounds towards negative infinity, and trunc, which rounds towards zero.

For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different. We use the Mathcad function mod(x,y), which returns x modulo y, and has the same sign as x.

Instructions

Enter two integers of your choice for Int1 and Int2.

(type into the right hand side of the 'Int1:= ' and 'Int2:=' statements, overwriting or modifying any numbers already there)

Implementation

Mathcad Input and Output

Mathcad "standard" input and output takes place directly on a worksheet ("program source code").

Inputs:

== the user types in values after := (definition) operator

Integer One: Int1:=-8

Integer Two: Int2:=3

Results:

== Mathcad automatically calculates and displays results after = (evaluation) operator.

sum  : Int1 + Int2 = -5

difference  : Int1 - Int2 = -11

product  : Int1 · Int2 = -24

integer quotient : floor(Int1÷Int2)=-3 trunc(Int1÷Int2)=-2

remainder  : mod(Int1,Int2)=-2

exponentiation  : Int1Int2=-512


MATLAB / 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)
a^b

Maxima

block(
   [a: read("a"), b: read("b")],
   print(a + b),
   print(a - b),
   print(a * b),
   print(a / b),
   print(quotient(a, b)),
   print(remainder(a, b)),
   a^b
);

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)

Mercury

:- module arith_int.
:- interface.

:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.
:- import_module int, list, string.

main(!IO) :-
    io.command_line_arguments(Args, !IO),
    ( if
        Args = [AStr, BStr],
        string.to_int(AStr, A),
        string.to_int(BStr, B)
      then
        io.format("A + B = %d\n", [i(A + B)], !IO),
        io.format("A - B = %d\n", [i(A - B)], !IO),
        io.format("A * B = %d\n", [i(A * B)], !IO),

        % Division: round towards zero.
        %
        io.format("A / B = %d\n", [i(A / B)], !IO),

        % Division: round towards minus infinity.
        %
        io.format("A div B = %d\n", [i(A div B)], !IO), 
    
        % Modulus: X mod Y = X - (X div Y) * Y.
        %
        io.format("A mod B = %d\n", [i(A mod B)], !IO),

        % Remainder: X rem Y = X - (X / Y) * Y.
        %
        io.format("A rem B = %d\n", [i(A rem B)], !IO),

        % Exponentiation is done using the function int.pow/2.
        %
        io.format("A `pow` B = %d\n", [i(A `pow` B)], !IO)
      else
        io.set_exit_status(1, !IO)
    ).

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

min

Works with: min version 0.37.0
('+ '- '* 'div 'mod)
(("Enter an integer" ask integer) 2 times) quote-map =>
("$1 -> $2" rollup concat dup -> quote prepend %) prepend
map "\n" join puts!
Output:
Enter an integer: -3
Enter an integer: 5
(-3 5 +) -> 2
(-3 5 -) -> -8
(-3 5 *) -> -15
(-3 5 div) -> 0
(-3 5 mod) -> -3

МК-61/52

П1	<->	П0
+	С/П
ИП0	ИП1	-	С/П
ИП0	ИП1	*	С/П
ИП0	ИП1	/	[x]	С/П
ИП0	^	ИП1	/	[x]	ИП1	*	-	С/П
ИП1	ИП0	x^y	С/П

ML/I

ML/I will read two integers from 'standard input' or similar, and then output the results to 'standard output' or similar.

MCSKIP "WITH" NL
"" Arithmetic/Integer
"" assumes macros on input stream 1, terminal on stream 2
MCSKIP MT,<>
MCINS %.
MCDEF SL SPACES NL AS <MCSET T1=%A1.
MCSET T2=%A2.
a + b   = %%T1.+%T2..
a - b   = %%T1.-%T2..
a * b   = %%T1.*%T2..
a / b   = %%T1./%T2..
a rem b = %%T1.-%%%T1./%T2..*%T2...
Division is truncated to the greatest integer
that does not exceed the exact result. Remainder matches
the sign of the second operand, if the signs differ.

Modula-2

MODULE ints;

IMPORT  InOut;

VAR     a, b    : INTEGER;

BEGIN
  InOut.WriteString ("Enter two integer numbers : ");   InOut.WriteBf;
  InOut.ReadInt (a);
  InOut.ReadInt (b);
  InOut.WriteString ("a + b   = ");  InOut.WriteInt (a + b, 9);    InOut.WriteLn;
  InOut.WriteString ("a - b   = ");  InOut.WriteInt (a - b, 9);    InOut.WriteLn;
  InOut.WriteString ("a * b   = ");  InOut.WriteInt (a * b, 9);    InOut.WriteLn;
  InOut.WriteString ("a / b   = ");  InOut.WriteInt (a DIV b, 9);  InOut.WriteLn;
  InOut.WriteString ("a MOD b = ");  InOut.WriteInt (a MOD b, 9);  InOut.WriteLn;
  InOut.WriteLn;
END ints.

Producing:

$$ ints
Enter two integer numbers : 12 7
a + b   =        19
a - b   =         5
a * b   =        84
a / b   =         1
a MOD b =         5

$$ ints
Enter two integer numbers : 123 -111
a + b   =        12
a - b   =       234
a * b   =    -13653
a / b   =        -1
a MOD b =        12

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.

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

Nanoquery

Translation of: Python
print "Number 1: "
x = int(input())
print "Number 2: "
y = int(input())

println format("Sum: %d", x + y)
println format("Difference: %d", x - y)
println format("Product: %d", x * y)
println format("Quotient: %f", x / y)

println format("Remainder: %d", x % y)
println format("Power: %d", x ^ y)
Output:
Number 1: 5
Number 2: 6
Sum: 11
Difference: -1
Product: 30
Quotient: 0.833333
Remainder: 5
Power: 15625

Nemerle

Adapted nearly verbatim from C# solution above. Note that I've used the exponentiation operator (**), but Math.Pow() as used in the C# solution would also work.

using System;
 
class Program
{
    static Main(args : array[string]) : void
    {
        def a = Convert.ToInt32(args[0]);
        def 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} ** {1} = {2}", a, b, a ** b);
    }
}

NetRexx

Translation of: REXX
/* NetRexx */

options replace format comments java crossref symbols binary

say "enter 2 integer values separated by blanks"
parse ask 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

return
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

NewLISP

; integer.lsp
; oofoe 2012-01-17

(define (aski msg) (print msg) (int (read-line)))
(setq x (aski "Please type in an integer and press [enter]: "))
(setq y (aski "Please type in another integer             : "))

; Note that +, -, *, / and % are all integer operations.
(println)
(println "Sum: " (+ x y))
(println "Difference: " (- x y))
(println "Product: " (* x y))
(println "Integer quotient (rounds to 0): " (/ x y))
(println "Remainder: " (setq r (% x y)))

(println "Remainder sign matches: "
	 (cond ((= (sgn r) (sgn x) (sgn y)) "both")
	       ((= (sgn r) (sgn x))         "first")
	       ((= (sgn r) (sgn y))         "second")))
	 
(println)
(println "Exponentiation: " (pow x y))

(exit) ; NewLisp normally goes to listener after running script.
Output:
Please type in an integer and press [enter]: 17
Please type in another integer             : -4

Sum: 13
Difference: 21
Product: -68
Integer quotient (rounds to 0): -4
Remainder: 1
Remainder sign matches: first

Exponentiation: 1.197303672e-005

Nial

Example tested with Q'Nial7.

Define new operator using an atlas of operators:

     arithmetic is OP A B{[first,last,+,-,*,quotient,mod,power] A B}

Test new operator:

     -23 arithmetic 7
-23 7 -16 -30 -161 -4 5 -3404825447

Negative divisors are not accepted for integer quotient quotient or remainder mod, and in both cases the result is an error with the message ?negative divisor.

For quotient, if the divisor B is zero, the result is zero.

For mod, if the divisor B is zero, the result is A.

The quotient on division by a positive integer B is always an integer on the same side of the origin as A.

Nial definition of quotient:

A quotient B =f=  floor (A / B)

floor rounds towards negative infinity (next lower integer).

Nim

import parseopt, strutils
 
var 
  opt: OptParser = initOptParser()
  str = opt.cmdLineRest.split
  a: int = 0
  b: int = 0
 
try:
  a = parseInt(str[0])
  b = parseInt(str[1])
except ValueError:
  quit("Invalid params. Two integers are expected.")
 
 
echo("a      : " & $a)
echo("b      : " & $b)
echo("a + b  : " & $(a+b))
echo("a - b  : " & $(a-b))
echo("a * b  : " & $(a*b))
echo("a div b: " & $(a div b)) # div rounds towards zero
echo("a mod b: " & $(a mod b)) # sign(a mod b)==sign(a) if sign(a)!=sign(b)
echo("a ^ b  : " & $(a ^ b))

Execute: Aritmint 4 5

Output:
a      : 4
b      : 5
a + b  : 9
a - b  : -1
a * b  : 20
a div b: 4
a mod b: 4
a ^ b  : 1024

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

Nu

Division rounds towards -infinity. Modulus will match the sign of the first number.

input | parse "{a} {b}" | first | values | into int | do {|a b|
	{
		Sum: ($a + $b)
		Difference: ($a - $b)
		Product: ($a * $b)
		Quotient: ($a // $b)
		Remainder: ($a mod $b)
		Exponent: ($a ** $b)
	}
} $in.0 $in.1
Output:
-1 2
╭────────────┬────╮
│ Sum        │ 1  │
│ Difference │ -3 │
│ Product    │ -2 │
│ Quotient   │ -1 │
│ Remainder  │ -1 │
│ Exponent   │ 1  │
╰────────────┴────╯

Nutt

module main
imports native.io{input.hear,output.say}

vals a=hear(Numerable),b=hear(Numerable)
say("a+b="+(a+b))
say("a-b="+(a-b))
say("a*b="+(a*b))
say("a//b="+(a//b))
say("a%b="+(a%b))
say("a^b="+(a^b))

end

Oberon-2

Oxford Oberon-2

MODULE Arithmetic;
IMPORT In, Out;
VAR
        x,y:INTEGER;
BEGIN
        Out.String("Give two numbers: ");In.Int(x);In.Int(y);
        Out.String("x + y >");Out.Int(x + y,6);Out.Ln;
        Out.String("x - y >");Out.Int(x - y,6);Out.Ln;
        Out.String("x * y >");Out.Int(x * y,6);Out.Ln;
        Out.String("x / y >");Out.Int(x DIV y,6);Out.Ln;
        Out.String("x MOD y >");Out.Int(x MOD y,6);Out.Ln;
END Arithmetic.
Output:
Give two numbers: 12 23
x + y >    35
x - y >   -11
x * y >   276
x / y >     0
x MOD y >    12

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);
    }
  }
}

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 *)

Oforth

: integers (a b -- )
   "a + b ="   . a b + .cr
   "a - b ="   . a b - .cr
   "a * b ="   . a b * .cr
   "a / b ="   . a b / .cr
   "a mod b =" . a b mod .cr 
   "a pow b =" . a b pow .cr
;
Output:
>12 23 integers
a + b = 35
a - b = -11
a * b = 276
a / b = 0
a mod b = 12
a pow b = 6624737266949237011120128
ok

Ol

(define a 8)
(define b 12)

(print "(+ " a " " b ") => "    (+ a b))
(print "(- " a " " b ") => "    (- a b))
(print "(* " a " " b ") => "    (* a b))
(print "(/ " a " " b ") => "    (/ a b))

(print "(quotient " a " " b ") => "  (quot a b)) ; same as (quotient a b)
(print "(remainder " a " " b ") => " (rem  a b)) ; same as (remainder a b)
(print "(modulo " a " " b ") => "    (mod  a b)) ; same as (modulo a b)

(print "(expt " a " " b ") => " (expt a b))
(print "(gcd " a " " b ") => " (gcd a b))
(print "(lcm " a " " b ") => " (lcm a b))

; you can use more than two arguments for +,-,*,/ functions
(print (+ 1 3 5 7 9))
(print (- 1 3 5 7 9))
(print (* 1 3 5 7 9)) ; same as (1*3*5*7*9)
(print (/ 1 3 5 7 9)) ; same as (((1/3)/5)/7)/9
Output:
(+ 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
(expt 8 12) => 68719476736
(gcd 8 12) => 4
(lcm 8 12) => 24
25
-23
945
1/945

Onyx

# Most of this long script is mere presentation.
# All you really need to do is push two integers onto the stack
# and then execute add, sub, mul, idiv, or pow.

$ClearScreen { # Using ANSI terminal control
  `\e[2J\e[1;1H' print flush
} bind def

$Say { # string Say -
  `\n' cat print flush
} bind def

$ShowPreamble {
`To show how integer arithmetic in done in Onyx,' Say
`we\'ll use two numbers of your choice, which' Say
`we\'ll call A and B.\n' Say
} bind def

$Prompt { # stack: string --
  stdout exch write pop flush
} def

$GetInt { # stack: name -- integer
  dup cvs `Enter integer ' exch cat `: ' cat
  Prompt stdin readline pop cvx eval def
} bind def

$Template { # arithmetic_operator_name label_string Template result_string
  A cvs ` ' B cvs ` ' 5 ncat over cvs ` gives ' 3 ncat exch
  A B dn cvx eval cvs `.' 3 ncat Say
} bind def

$ShowResults {
  $add `Addition: ' Template
  $sub `Subtraction: ' Template
  $mul `Multiplication: ' Template
  $idiv `Division: ' Template
  `Note that the result of integer division is rounded toward zero.' Say
  $pow `Exponentiation: ' Template
  `Note that the result of raising to a negative power always gives a real number.' Say
} bind def

ClearScreen ShowPreamble $A GetInt $B GetInt ShowResults
Output:
To show how integer arithmetic in done in Onyx,
we'll use two numbers of your choice, which
we'll call A and B.

Enter integer A: 34
Enter integer B: 2
Addition: 34 2 add gives 36.
Subtraction: 34 2 sub gives 32.
Multiplication: 34 2 mul gives 68.
Division: 34 2 idiv gives 17.
Note that the result of integer division is rounded toward zero.
Exponentiation: 34 2 pow gives 1156.
Note that the result of raising to a negative power always gives a real number.

Openscad

echo (a+b);  /* Sum */
echo (a-b);  /* Difference */
echo (a*b);  /* Product */
echo (a/b);  /* Quotient */
echo (a%b);  /* Modulus */

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}

Panda

Use reflection to get all functions defined on numbers taking number and returning number.

a=3 b=7 func:_bbf__number_number_number =>f.name.<b> '(' a b ')' ' => ' f(a b) nl
Output:
atan2 ( 3 7 ) => 0.40489178628508343 
divide ( 3 7 ) => 0.42857142857142855 
gt ( 3 7 ) => UNDEFINED! 
gte ( 3 7 ) => UNDEFINED! 
lt ( 3 7 ) => 3 
lte ( 3 7 ) => 3 
max ( 3 7 ) => 7 
min ( 3 7 ) => 3 
minus ( 3 7 ) => -4 
mod ( 3 7 ) => 3 
plus ( 3 7 ) => 10 
pow ( 3 7 ) => 2187

PARI/GP

Integer division with \ rounds to . There also exists the \/ round-to-nearest (ties to ) operator. Ordinary division / does not round but returns rationals if given integers with a non-integral quotient.

arith(a,b)={
  print(a+b);
  print(a-b);
  print(a*b);
  print(a\b);
  print(a%b);
  print(a^b);
};

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);
 writeln('a^b = ',Power(a,b):4:2);    {real power}
 writeln('a^b = ',IntPower(a,b):4:2); {integer power}
end.

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"
    ;

Phix

Library: Phix/pGUI
Library: Phix/online

You can run this online here (layout/space is not perfected yet).

with javascript_semantics
include pGUI.e

Ihandle lab, tab, res, dlg

constant fmt = """
a = %d
b = %d
a + b = %d
a - b = %d
a * b = %d
a / b = %g  (does not truncate)
remainder(a,b) = %d (same sign as first operand)
power(a,b) = %g
"""

function valuechanged_cb(Ihandle tab)
    string s = IupGetAttribute(tab,"VALUE")
    sequence r = scanf(s,"%d %d")
    if length(r)=1 then
        integer {a,b} = r[1]
        s = sprintf(fmt, {a, b, a+b, a-b, a*b, a/b, remainder(a,b), power(a,b)})
        IupSetStrAttribute(res,"TITLE",s)
        IupRefresh(res)
    end if
    return IUP_DEFAULT
end function

procedure main()
    IupOpen()
    lab = IupLabel("Enter two numbers")
    tab = IupText("VALUECHANGED_CB", Icallback("valuechanged_cb"),"EXPAND=HORIZONTAL")
    res = IupLabel("(separated by a space)\n\n\n\n\n\n\n","EXPAND=BOTH")
    dlg = IupDialog(IupVbox({IupHbox({lab,tab},"GAP=10,NORMALIZESIZE=VERTICAL"),
                             IupHbox({res})},"MARGIN=5x5"),
                            `SIZE=188x112,TITLE="Arithmetic/Integer"`)
    IupShow(dlg)
    if platform()!=JS then
        IupMainLoop()
        IupClose()
    end if
end procedure
 
main()
Output:

With an input of "2 3"

a = 2
b = 3
a + b = 5
a - b = -1
a * b = 6
a / b = 0.666667  (does not truncate)
remainder(a,b) = 2 (same sign as first operand)
power(a,b) = 8

Phixmonti

def printOp
    swap print print nl
enddef

8 var a 3 var b
"a = " a printOp
"b = " b printOp

"a + b = " a b + printOp
"a - b = " a b - printOp
"a * b = " a b * printOp
"int(a / b) = " a b / int printOp
"a mod b = " a b mod printOp
"a ^ b = " a b power printOp

PHL

module arith;

extern printf;
extern scanf;

@Integer main [
	@Pointer<@Integer> a = alloc(4);
	@Pointer<@Integer> b = alloc(4);
	scanf("%i %i", a, b);
	
	printf("a + b = %i\n", a::get + b::get);
	printf("a - b = %i\n", a::get - b::get);
	printf("a * b = %i\n", a::get * b::get);
	printf("a / b = %i\n", a::get / b::get);
	printf("a % b = %i\n", a::get % b::get);
	printf("a ** b = %i\n", a::get ** b::get);
	
	return 0;
]

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",
    "power:               ", $a ** $b, "\n"; // PHP 5.6+ only
?>

Picat

main =>
    X = read_int(),
    Y = read_int(),
    foreach (Op in [+,-,*,div,rem])
        R = apply(Op,X,Y),
        printf("%d %w %d = %d\n", X, Op, Y, R)
    end.
Output:
2 3
2 + 3 = 5
2 - 3 = -1
2 * 3 = 6
2 div 3 = 0
2 rem 3 = 2

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)) )

Piet



command   stack
in(int)   A
duplicate AA
duplicate AAA
duplicate AAAA
duplicate AAAAA
in(int)   BAAAAA
duplicate BBAAAAA
duplicate BBBAAAAA
duplicate BBBBAAAAA
duplicate BBBBBAAAAA
push 9    9BBBBBAAAAA
push 1    19BBBBBAAAAA
roll      BBBBAAAABA
push 7    7BBBBAAAABA
push 1    17BBBBAAAABA
roll      BBBAAABABA
push 5    5BBBAAABABA
push 1    15BBBAAABABA
roll      BBAABABABA
push 3    3BBAABABABA
push 1    13BBAABABABA
roll      BABABABABA
add       (A+B)BABABABA
out(int)  BABABABA
sub       (A-B)BABABA
out(int)  BABABA
mult      (A*B)BABA
out(int)  BABA
divide    (A/B)BA
out(int)  BA
mod       (A%B)
out(int)  NULL
push 1    1
exit

How rounding is handled is up to the interpreter, but I believe the intent was round towards 0.

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)); /* truncates towards zero.       */
put skip list (mod(a, b));  /* Remainder is always positive. */
put skip list (rem(a, b));  /* Sign can be negative.         */

Plain English

To run:
Start up.
Demonstrate integer arithmetic.
Wait for the escape key.
Shut down.

To demonstrate integer arithmetic:
Write "Enter a number: " to the console without advancing.
Read a number from the console.
Write "Enter another number: " to the console without advancing.
Read another number from the console.
Show the arithmetic operations between the number and the other number.

To show the arithmetic operations between a number and another number:
Write the number plus the other number then " is the sum." to the console.
Write the number minus the other number then " is the difference." to the console.
Write the number times the other number then " is the product." to the console.
Show the division of the number by the other number.
Raise the number to the other number.
Write the number then " is the power." to the console.

To show the division of a number by another number:
Privatize the number.
Divide the number by the other number giving a quotient [rounding toward zero] and a remainder [with the same sign as the dividend].
Write the quotient then " is the quotient." to the console.
Write the remainder then " is the remainder." to the console.
Output:
Enter a number: 44
Enter another number: 3
47 is the sum.
41 is the difference.
132 is the product.
14 is the quotient.
2 is the remainder.
85184 is the power.

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');

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

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, round to even:          $([Math]::Round($a / $b))"
Write-Host "Remainder, sign follows first:    $($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)

Processing

int a = 7, b = 5;

println(a + " + " + b + " = " + (a + b));
println(a + " - " + b + " = " + (a - b));
println(a + " * " + b + " = " + (a * b));
println(a + " / " + b + " = " + (a / b)); //Rounds towards zero
println(a + " % " + b + " = " + (a % b)); //Same sign as first operand
Output:
7 + 5 = 12
7 - 5 = 2
7 * 5 = 35
7 / 5 = 1
7 % 5 = 2

ProDOS

IGNORELINE Note: This example includes the math module.
include arithmeticmodule
:a
editvar /newvar /value=a /title=Enter first integer: 
editvar /newvar /value=b /title=Enter second integer:
editvar /newvar /value=c 
do add -a-,-b-=-c-
printline -c-
do subtract a,b
printline -c-
do multiply a,b
printline -c-
do divide a,b
printline -c-
do modulus a,b
printline -c-
editvar /newvar /value=d /title=Do you want to calculate more numbers?
if -d- /hasvalue yes goto :a else goto :end
:end
IGNORELINE Note: This example does not use the math module.
:a
editvar /newvar /value=a /title=Enter first integer: 
editvar /newvar /value=b /title=Enter second integer:
editvar /newvar /value=-a-+-b-=-c-
printline -c-
editvar /newvar /value=a*b=c
printline -c-
editvar /newvar /value=a/b=c
printline -c-
editvar /newvar /value=a %% b=c
printline -c-
editvar /newvar /value=d /title=Do you want to calculate more numbers?
if -d- /hasvalue yes goto :a else goto :end
:end

Prolog

Integer quotient (`//`) rounds towards 0.

Remainder (`rem`) matches the sign of its first operand.

print_expression_and_result(M, N, Operator) :-
    Expression =.. [Operator, M, N],
    Result is Expression,
    format('~w ~8|is ~d~n', [Expression, Result]).

arithmetic_integer :-
    read(M),
    read(N),
    maplist( print_expression_and_result(M, N), [+,-,*,//,rem,^] ).

Use thus:

?- arithmetic_integer.
|: 5.
|: 7.
5+7     is 12
5-7     is -2
5*7     is 35
5//7    is 0
5 rem 7 is 5
5^7     is 78125
true.

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()

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)
print "Power: %d" % 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.

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
12 ** 8	=> 429981696
Number 1: 20
Number 2: 4
20 + 4  => 24
20 - 4  => 16
20 * 4  => 80
20 // 4 => 5
20 % 4  => 0
20 ** 4 => 160000

Python 3.x Long Form

input1 = 18
# input1 = input()
input2 = 7
# input2 = input()

qq = input1 + input2
print("Sum: 		  " + str(qq))
ww = input1 - input2
print("Difference: 	  " + str(ww))
ee = input1 * input2
print("Product: 	  " + str(ee))
rr = input1 / input2
print("Integer quotient: " + str(int(rr)))
print("Float quotient:   " + str(float(rr)))
tt = float(input1 / input2)
uu = (int(tt) - float(tt))*-10
#print(tt)
print("Whole Remainder:  " + str(int(uu)))
print("Actual Remainder: " + str(uu))
yy = input1 ** input2
print("Exponentiation:   " + str(yy))
Output:
Sum: 		  25
Difference: 	  11
Product: 	  126
Integer quotient: 2
Float quotient:   2.5714285714285716
Whole Remainder:  5
Actual Remainder: 5.714285714285716
Exponentiation:   612220032

QB64

CBTJD: 2020/03/12

START:
INPUT "Enter two integers (a,b):"; a!, b!
IF a = 0 THEN END
IF b = 0 THEN
    PRINT "Second integer is zero. Zero not allowed for Quotient or Remainder."
    GOTO START
END IF
PRINT
PRINT "             Sum = "; a + b
PRINT "      Difference = "; a - b
PRINT "         Product = "; a * b
' Notice the use of the INTEGER Divisor "\" as opposed to the regular divisor "/".
PRINT "Integer Quotient = "; a \ b, , "* Rounds toward 0."
PRINT "       Remainder = "; a MOD b, , "* Sign matches first operand."
PRINT "  Exponentiation = "; a ^ b
PRINT
INPUT "Again? (y/N)"; a$
IF UCASE$(a$) = "Y" THEN CLS: GOTO START
CLS
END

Quackery

  $ "Please enter two integers separated by a space. "
  input quackery
  2dup say "Their sum is:              " +    echo cr
  2dup say "Their difference is:       " -    echo cr
  2dup say "Their product is: "        " *    echo cr
  2dup say "Their integer quotient is: " /    echo cr
  2dup say "Their remainder is:        " mod  echo cr
       say "Their exponentiation is:   " **   echo cr
  cr
  say "Quotient rounds towards negative infinity." cr
  say "Remainder matches the sign of the second argument."
Output:
Please enter two integers separated by a space. 543 21
Their sum is: 564
Their difference is: 522
Their product is: 11403
Their integer quotient is: 25
Their remainder is: 18
Their exponentiation is: 2696475144200627485897267767746883957141292127831428752543

R

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

Racket

#lang racket/base

(define (arithmetic x y)
  (for ([op (list + - * / quotient remainder modulo max min gcd lcm)])
    (printf "~s => ~s\n" `(,(object-name op) ,x ,y) (op x y))))

(arithmetic 8 12)
Output:
(+ 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

Raku

(formerly Perl 6)

Note that div requires integer arguments. If you want integer division with other types, say floor($a/$b).

my Int $a = get.floor;
my Int $b = get.floor;

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;

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

REBOL

REBOL [
	Title: "Integer"
	URL: http://rosettacode.org/wiki/Arithmetic/Integer
]

x: to-integer ask "Please type in an integer, and press [enter]: "
y: to-integer ask "Please enter another integer: "
print ""

print ["Sum:"  x + y]
print ["Difference:"  x - y]
print ["Product:" x * y]

print ["Integer quotient (coercion)                          :"  to-integer x / y]
print ["Integer quotient (away from zero)                    :"  round x / y]
print ["Integer quotient (halves round towards even digits)  :"  round/even x / y]
print ["Integer quotient (halves round towards zero)         :"  round/half-down x / y]
print ["Integer quotient (round in negative direction)       :"  round/floor x / y]
print ["Integer quotient (round in positive direction)       :"  round/ceiling x / y]
print ["Integer quotient (halves round in positive direction):"  round/half-ceiling x / y]

print ["Remainder:"  r: x // y]

; REBOL evaluates infix expressions from left to right. There are no
; precedence rules -- whatever is first gets evaluated. Therefore when
; performing this comparison, I put parens around the first term
; ("sign? a") of the expression so that the value of /a/ isn't
; compared to the sign of /b/. To make up for it, notice that I don't
; have to use a specific return keyword. The final value in the
; function is returned automatically.

match?: func [a b][(sign? a) = sign? b]

result: copy []
if match? r x [append result "first"]
if match? r y [append result "second"]

; You can evaluate arbitrary expressions in the middle of a print, so
; I use a "switch" to provide a more readable result based on the
; length of the /results/ list.

print [
	"Remainder sign matches:" 
	switch length? result [
		0 ["neither"]
		1 [result/1]
		2 ["both"]
	] 
]

print ["Exponentiation:" x ** y]
Output:
Please type in an integer, and press [enter]: 17
Please enter another integer: -4

Sum: 13
Difference: 21
Product: -68
Integer quotient (coercion)                          : -4
Integer quotient (away from zero)                    : -4
Integer quotient (halves round towards even digits)  : -4
Integer quotient (halves round towards zero)         : -4
Integer quotient (round in negative direction)       : -5
Integer quotient (round in positive direction)       : -4
Integer quotient (halves round in positive direction): -4
Remainder: 1
Remainder sign matches: first
Exponentiation: 1.19730367213036E-5

Relation

There is no input, variables have to be set in code. Format is there only for output.

set a = -17
set b = 4
echo "a+b = ".format(a+b,"%1d")
echo "a-b = ".format(a-b,"%1d")
echo "a*b = ".format(a*b,"%1d")
echo "a DIV b = ".format(floor(a/b),"%1d")
echo "a MOD b = ".format(a mod b,"%1d")
echo "a^b = ".format(pow(a,b),"%1d")

ReScript

let a = int_of_string(Sys.argv[2])
let b = int_of_string(Sys.argv[3])

let sum = a + b
let difference = a - b
let product = a * b
let division = a / b
let remainder = mod(a, b)

Js.log("a + b = " ++ string_of_int(sum))
Js.log("a - b = " ++ string_of_int(difference))
Js.log("a * b = " ++ string_of_int(product))
Js.log("a / b = " ++ string_of_int(division))
Js.log("a % b = " ++ string_of_int(remainder))
Output:
$ bsc arith.res > arith.bs.js
$ node arith.bs.js 10 7
a + b = 17
a - b = 3
a * b = 70
a / b = 1
a % b = 3

Retro

Retro's arithmetic functions are based on those in Forth. The example is an adaption of the one from Forth.

:arithmetic (ab-)
  over       '\na_______=_%n s:put
  dup        '\nb_______=_%n s:put
  dup-pair + '\na_+_b___=_%n s:put
  dup-pair - '\na_-_b___=_%n s:put
  dup-pair * '\na_*_b___=_%n s:put
  /mod       '\na_/_b___=_%n s:put
             '\na_mod_b_=_%n\n" s:put ;

REXX

All operators automatically produce integers where appropriate   (up to twenty decimal digits in the program below),
or numbers in exponential format when necessary.   (The REXX default is   9   decimal digits.)

For division that produces a floating point number, the result is rounded to the nearest number that can be expressed
within the current number of decimal digits   (in the example program below, it is   20   decimal digits).

/*REXX program obtains two integers from the C.L. (a prompt);  displays some operations.*/
numeric digits 20                                /*#s are round at 20th significant dig.*/
parse arg x y .                                  /*maybe the integers are on the  C.L.  */

  do while \datatype(x,'W') | \datatype(y,'W')   /*both   X  and  Y   must be integers. */
  say "─────Enter two integer values  (separated by blanks):"
  parse pull x y .                               /*accept two thingys from command line.*/
  end   /*while*/
                                                 /* [↓]  perform this  DO  loop twice.  */
     do j=1  for 2                               /*show  A  oper  B,   then  B  oper  A.*/
     call show 'addition'          ,  "+",   x+y
     call show 'subtraction'       ,  "-",   x-y
     call show 'multiplication'    ,  "*",   x*y
     call show 'int  division'     ,  "%",   x%y,  '    [rounds down]'
     call show 'real division'     ,  "/",   x/y
     call show 'division remainder',  "//",  x//y, '    [sign from 1st operand]'
     call show 'power'             ,  "**",  x**y

     parse value  x  y    with    y  x           /*swap the two values and perform again*/
     if j==1  then say copies('═', 79)           /*display a fence after the 1st round. */
     end   /*j*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: parse arg c,o,#,?;   say right(c,25)' '  x  center(o,4)  y  " ───► "  #  ?;   return
output   when using the input of:     4   -17
                 addition  4  +   -17  ───►  -13
              subtraction  4  -   -17  ───►  21
           multiplication  4  *   -17  ───►  -68
            int  division  4  %   -17  ───►  0     [rounds down]
            real division  4  /   -17  ───►  -0.23529411764705882353
       division remainder  4  //  -17  ───►  4     [sign from 1st operand]
                    power  4  **  -17  ───►  5.8207660913467407227E-11
═══════════════════════════════════════════════════════════════════════════════
                 addition  -17  +   4  ───►  -13
              subtraction  -17  -   4  ───►  -21
           multiplication  -17  *   4  ───►  -68
            int  division  -17  %   4  ───►  -4     [rounds down]
            real division  -17  /   4  ───►  -4.25
       division remainder  -17  //  4  ───►  -1     [sign from 1st operand]
                    power  -17  **  4  ───►  83521

Ring

func Test a,b
   see "a+b" + ( a + b ) + nl
   see "a-b" + ( a - b ) + nl
   see "a*b" + ( a * b ) + nl
   // The quotient isn't integer, so we use the Ceil() function, which truncates it downward.
   see "a/b" + Ceil( a / b ) + nl
   // Remainder:
   see "a%b" + ( a % b ) + nl
   see "a**b" +  pow(a,b )  + nl

Robotic

input string "Enter number 1:"
set "a" to "input"
input string "Enter number 2:"
set "b" to "input"

[ "Sum: ('a' + 'b')"
[ "Difference: ('a' - 'b')"
[ "Product: ('a' * 'b')"
[ "Integer Quotient: ('a' / 'b')"
[ "Remainder: ('a' % 'b')"
[ "Exponentiation: ('a'^'b')"

RPL

≪ → a b 
  ≪ "a + b = " a b + →STR +
     "a - b = " a b - →STR +
     "a * b = " a b * →STR +
     "a / b = " a b / →STR +
     "a % b = " a b / LAST ROT * - →STR +
     "a ^ b = " a B→R b B→R ^ R→B →STR +
≫ ≫ 'SHOWA' STO
#14 #3 SHOWA
6:     "a + b = # 17d" 
5:     "a - b = # 11d" 
4:     "a * b = # 42d" 
3:      "a / b = # 4d" 
2:      "a % b = # 2d" 
1:   "a ^ b = # 2744d" 

Ruby

puts 'Enter x and y'
x = gets.to_i  # to check errors, use x=Integer(gets)
y = gets.to_i

puts "Sum: #{x+y}",
     "Difference: #{x-y}",
     "Product: #{x*y}",
     "Quotient: #{x/y}",       # truncates towards negative infinity
     "Quotient: #{x.fdiv(y)}", # float
     "Remainder: #{x%y}",      # same sign as second operand
     "Exponentiation: #{x**y}",
     "Quotient: %d with Remainder: %d" % x.divmod(y)

Run BASIC

input "1st integer: "; i1
input "2nd integer: "; i2
 
print "      Sum"; i1 + i2
print "     Diff"; i1 - i2
print "  Product"; i1 * i2
if i2 <>0 then print "  Quotent "; int( i1 / i2); else print "Cannot divide by zero."
print "Remainder"; i1 MOD i2
print "1st raised to power of 2nd"; i1 ^ i2

Rust

Note that this code cannot be run within the Rust playpen as it does not support console input.

use std::env;

fn main() {
    let args: Vec<_> = env::args().collect();
    let a = args[1].parse::<i32>().unwrap();
    let b = args[2].parse::<i32>().unwrap();

    println!("sum:              {}", a + b);
    println!("difference:       {}", a - b);
    println!("product:          {}", a * b);
    println!("integer quotient: {}", a / b); // truncates towards zero
    println!("remainder:        {}", a % b); // same sign as first operand
}

Sass/SCSS

@function arithmetic($a,$b) {
	@return $a + $b, $a - $b, $a * $b, ($a - ($a % $b))/$b, $a % $b;
}

Which you use with:

nth(arithmetic(10,3),1);

Or each of the functions separately:

@function sum($a,$b) {
	@return $a + $b;
}

@function difference($a,$b) {
	@return $a - $b;
}

@function product($a,$b) {
	@return $a * $b;
}

@function integer-division($a,$b) {
	@return ($a - ($a % $b))/$b;
}

@function remainder($a,$b) {
	@return $a % $b;
}

@function float-division($a,$b) {
	@return $a / $b;
}

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

Scheme

(define (arithmetic x y)
  (for-each (lambda (op)
              (write  (list op x y))
              (display " => ")
              (write ((eval op) x y))
              (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

Seed7

$ include "seed7_05.s7i";

const proc: main is func
  local
    var integer: a is 0;
    var integer: b is 0;
  begin
    write("a = ");
    readln(a);
    write("b = ");
    readln(b);
 
    writeln("a + b = " <& a + b);
    writeln("a - b = " <& a - b);
    writeln("a * b = " <& a * b);
    writeln("a div b = " <& a div b);    # Rounds towards zero
    writeln("a rem b = " <& a rem b);    # Sign of the first operand
    writeln("a mdiv b = " <& a mdiv b);  # Rounds towards negative infinity
    writeln("a mod b = " <& a mod b);    # Sign of the second operand
  end func;

SenseTalk

ask "Enter the first number:"
put it into number1

ask "Enter the second number:"
put it into number2

put "Sum: " & number1 plus number2
put "Difference: " & number1 minus number2
put "Product: " & number1 multiplied by number2
put "Integer quotient: " & number1 div number2 -- Rounding towards 0
put "Remainder: " & number1 rem number2
put "Exponentiation: " & number1 to the power of number2

Sidef

var a = Sys.scanln("First number: ").to_i;
var b = Sys.scanln("Second number: ").to_i;

%w'+ - * // % ** ^ | & << >>'.each { |op|
    "#{a} #{op} #{b} = #{a.$op(b)}".say;
}
Output:
First number: 1234
Second number: 7
1234 + 7 = 1241
1234 - 7 = 1227
1234 * 7 = 8638
1234 // 7 = 176
1234 % 7 = 2
1234 ** 7 = 4357186184021382204544
1234 ^ 7 = 1237
1234 | 7 = 1239
1234 & 7 = 2
1234 << 7 = 157952
1234 >> 7 = 9

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: ')}.

SmallBASIC

input "Enter first number : "; A
input "Enter second number: "; B

print "Sum       : "; A + B
print "Difference: "; A - B
print "Product   : "; A * B
print "Quotient  : "; A \ B     ' Integer quotient rounds towards smaller number
print "Remainder : "; A % B     ' sign of remainder is given by sign of first operand
print "Power     : "; A ^ B

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.
Works with: Smalltalk/X

(and all other Smalltalks)

|a b|
a := (Dialog request:'Enter first number:') asNumber.
b := (Dialog request:'Enter second number:') asNumber.
#( + - / * // \\ quo: rem: raisedTo: **) do:[:operator |
    |result|
    result := a perform:operator with:b.
    '%P %s %P => %P\n' printf:{a . operator . b . result} on:Transcript
].

/ is exact division
// is truncating division (towards negative infinity)
\\ is remainder from \\
quo: is truncating division (towards zero)
\\ is remainder from quo:
** is just an alias for raisedTo:

Entering 10 and 3, generates:

Output:
10 + 3 => 13
10 - 3 => 7
10 / 3 => (10/3)
10 * 3 => 30
10 // 3 => 3
10 \\ 3 => 1
10 quo: 3 => 3
10 rem: 3 => 1
10 raisedTo: 3 => 1000
10 ** 3 => 1000

Entering 10 and -3 generates:

Output:
10 + -3 => 7
10 - -3 => 13
10 / -3 => (-10/3)
10 * -3 => -30
10 // -3 => -4
10 \\ -3 => -2
10 quo: -3 => -3
10 rem: -3 => 1
10 raisedTo: -3 => (1/1000)
10 ** -3 => (1/1000)

Entering 20 and 50 generates (notice the fraction and the long integer results):

Output:
20 + 50 => 70
20 - 50 => -30
20 / 50 => (2/5)
20 * 50 => 1000
20 // 50 => 0
20 \\ 50 => 20
20 quo: 50 => 0
20 rem: 50 => 20
20 raisedTo: 50 => 112589990684262400000000000000000000000000000000000000000000000000
20 ** 50 => 112589990684262400000000000000000000000000000000000000000000000000

smart BASIC

INPUT "Enter first number.":first
INPUT "Enter second number.":second
PRINT "The sum of";first;"and";second;"is ";first+second&"."
PRINT "The difference between";first;"and";second;"is ";ABS(first-second)&"."
PRINT "The product of";first;"and";second;"is ";first*second&"."
IF second THEN
    PRINT "The integer quotient of";first;"and";second;"is ";INTEG(first/second)&"."
ELSE
    PRINT "Division by zero not cool."
ENDIF
PRINT "The remainder being...";first%second&"."
PRINT STR$(first);"raised to the power of";second;"is ";first^second&"."

NOTES: Some curious aspects of smart BASIC to note in this code example:

  1. In smart BASIC, The command INTEG is a true integer function providing only the value of the characteristic. The smart BASIC INT command calculates as a rounding function. This differs from some other versions of BASIC.
  2. smart BASIC automatically inserts spaces ahead of and behind numbers. This can cause unexpected formatting issues when combining output from numeric variables with text. In order to suppress the trailing space, you must use the ampersand (&) to concatenate the numeric value with the following text (in this case, a period at the end of each sentence). In the case of leading spaces, you must convert the numeric value to text using the STR$ command (as with the last line of the code).

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)
	output = "expo  = " first ** second
end

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
 @    /-\
 \?\<!\?/#!===+<<<\      /-\
 | \<==@\>@\>>!/?!/=<?\>!\?/<<#
 |      |  |  #\->->+</
 |      \=!\=?!/->>+<<?\#
 @            #\?<<+>>-/
 \=@@@+@+++++#
 .
 <
 @
 \=@@@+@+++++#
 .
 #

SQL

Works with: Oracle
-- test.sql
-- Tested in SQL*plus

drop table test;

create table test (a integer, b integer);

insert into test values ('&&A','&&B');

commit;

select a-b difference from test;

select a*b product from test;

select trunc(a/b) integer_quotient from test;  

select mod(a,b) remainder from test;

select power(a,b) exponentiation from test;
SQL> @test.sql

Table dropped.


Table created.

Enter value for a: 3
Enter value for b: 4
old   1: insert into test values ('&&A','&&B')
new   1: insert into test values ('3','4')

1 row created.


Commit complete.


DIFFERENCE
----------
        -1


   PRODUCT
----------
        12


INTEGER_QUOTIENT
----------------
               0


 REMAINDER
----------
         3


EXPONENTIATION
--------------
            81
   

SSEM

The only operation that the SSEM supports natively is substraction. This program uses the 001 Sub. instruction to find the difference between a and b, assuming they are loaded into storage addresses 20 and 21 respectively.

00101000000000100000000000000000   0. -20 to c
10100000000001100000000000000000   1. c to 5
10100000000000100000000000000000   2. -5 to c
10101000000000010000000000000000   3. Sub. 21
00000000000001110000000000000000   4. Stop
00000000000000000000000000000000   5. 0

The routine is slightly more complicated than it would otherwise be, because the SSEM cannot load a value into the accumulator (c register) from storage without negating it in the process—so we have to shuffle the negation of a back out into storage and then negate it again before we can subtract b from it. This does, however, make it easy to implement addition using negation and subtraction. In this program, we first negate a; then subtract b, and store the result; and finally negate that result, thereby obtaining the sum of the two integers.

00101000000000100000000000000000   0. -20 to c
10101000000000010000000000000000   1. Sub. 21
10100000000001100000000000000000   2. c to 5
10100000000000100000000000000000   3. -5 to c
00000000000001110000000000000000   4. Stop
00000000000000000000000000000000   5. 0

A multiplication program will be found at Function definition#SSEM, and one that performs integer division at Loops/For with a specified step#SSEM.

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

Swift

let a = 6 
let b = 4

print("sum =\(a+b)")
print("difference = \(a-b)")
print("product = \(a*b)")
print("Integer quotient = \(a/b)")
print("Remainder = (a%b)")
print("No operator for Exponential")

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.

Terraform

HCL doesn't have an exponentiation operator and even integer division is contrived as shown in the code, but at least it prints the output variables alphabetically without any effort.......

#Aamrun, 15th August 2022

variable "a" {
  type = number
}

variable "b" {
  type = number
}

output "Sum" {
  value = var.a + var.b
}

output "Difference" {
  value = var.a - var.b
}

output "Product" {
  value = var.a * var.b
}

output "Quotient" {
  value = floor(var.a / var.b)
}

output "Remainder" {
  value = var.a % var.b
}

The floor function rounds to the closest lowest integer. Invocation and output are as below :

Output:
$ terraform apply -var="a=19" -var="b=7" -auto-approve

Changes to Outputs:
  + Difference = 12
  + Product    = 133
  + Quotient   = 2
  + Remainder  = 5
  + Sum        = 26

You can apply this plan to save these new output values to the Terraform state, without changing any real infrastructure.

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

Difference = 12
Product = 133
Quotient = 2
Remainder = 5
Sum = 26
$

TI-83 BASIC

Pauses added due to TI-83's lack of screen size.

Prompt A,B
Disp "SUM"
Pause A+B
Disp "DIFFERENCE"
Pause A-B
Disp "PRODUCT"
Pause AB
Disp "INTEGER QUOTIENT"
Pause int(A/B)
Disp "REMAINDER"
Pause A-B*int(A/B)

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))

Toka

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

TUSCRIPT

$$ MODE TUSCRIPT
a=5
b=3
c=a+b
c=a-b
c=a*b
c=a/b
c=a%b
Output:
a=5
b=3
c=a+b
c            = 8
c=a-b
c            = 2
c=a*b
c            = 15
c=a/b
c            = 1
c=a%b
c            = 2

UNIX Shell

The Unix shell does not directly support arithmetic operations, so external tools, such as expr are used to perform arithmetic calculations when required:

Works with: Bourne Shell
Works with: Almquist 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: Bourne Again SHell version 3.2
Works with: pdksh 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 $((...)) can be inside or outside the double quotes, but the `...` expressions from the previous example can also be inside or outside the double quotes.

Ursa

#
# integer arithmetic
#

decl int x y
out "number 1: " console
set x (in int console)
out "number 2: " console
set y (in int console)

out "\nsum:\t" (int (+ x y)) endl console
out "diff:\t" (int (- x y)) endl console
out "prod:\t" (int (* x y)) endl console
# quotient doesn't round at all, but the int function rounds up
out "quot:\t" (int (/ x y)) endl console
# mod takes the sign of x
out "mod:\t" (int (mod x y)) endl console

Sample session:

number 1: 15
number 2: 7

sum:	22
diff:	8
prod:	105
quot:	2
mod:	1

VBA

'Arithmetic - Integer
Sub RosettaArithmeticInt()
Dim opr As Variant, a As Integer, b As Integer
On Error Resume Next

a = CInt(InputBox("Enter first integer", "XLSM | Arithmetic"))
b = CInt(InputBox("Enter second integer", "XLSM | Arithmetic"))

Debug.Print "a ="; a, "b="; b, vbCr
For Each opr In Split("+ - * / \ mod ^", " ")
    Select Case opr
        Case "mod":     Debug.Print "a mod b", a; "mod"; b, a Mod b
        Case "\":       Debug.Print "a \ b", a; "\"; b, a \ b
        Case Else:      Debug.Print "a "; opr; " b", a; opr; b, Evaluate(a & opr & b)
    End Select
Next opr
End Sub

VBScript

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

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

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

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

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)


Verilog

module main;
  integer a, b;
  integer suma, resta, producto;
  integer division, resto, expo;
  
  initial begin
    a = -12;
    b = 7;
    
    suma = a + b;
    resta = a - b;
    producto = a * b;
    division = a / b;
    resto = a % b;
    expo = a ** b;
    
    $display("Siendo dos enteros a = -12 y b = 7");
    $display("       suma de a + b = ", suma);
    $display("      resta de a - b = ", resta);
    $display("   producto de a * b = ", producto);
    $display("   división de a / b = ", division);
    $display("   resto de a mod  b = ", resto);
    $display("exponenciación a ^ b = ", expo);
    $finish ;
  end
endmodule

Vim Script

let a = float2nr(input("Number 1: ") + 0)
let b = float2nr(input("Number 2: ") + 0)
echo "\nSum: " . (a + b)
echo "Difference: " . (a - b)
echo "Product: " . (a * b)
" The result of an integer division is truncated
echo "Quotient: " . (a / b)
" The sign of the result of the remainder operation matches the sign of 
" the first operand 
echo "Remainder: " . (a % b)

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

V (Vlang)

// Arithmetic-integer in V (Vlang)
// Tectonics: v run arithmetic-integer.v
module main
import math
import os

// starts here
pub fn main() {
    mut a := 0
    mut b := 0

    // get numbers from console
    print("Enter two integer numbers, separated by a space: ")
    text := os.get_raw_line()
    values := text.split(' ')
    a = values[0].int()
    b = values[1].int()

    // 4 basics, remainder, no exponentiation operator
    println("values:           a $a, b $b")
    println("sum:              a + b = ${a + b}")
    println("difference:       a - b = ${a - b}")
    println("product:          a * b = ${a * b}")
    println("integer quotient: a / b = ${a / b}, truncation")
    println("remainder:        a % b = ${a % b}, sign follows dividend")

    println("no exponentiation operator")
    println("  math.pow:    pow(a,b) = ${math.pow(a,b)}")
}
Output:
prompt$ v run arithmetic-integer.v
Enter two integer numbers, separated by a space: -5 3
values:           a -5, b 3
sum:              a + b = -2
difference:       a - b = -8
product:          a * b = -15
integer quotient: a / b = -1, truncation
remainder:        a % b = -2, sign follows dividend
no exponentiation operator
  math.pow:    pow(a,b) = -125

Wart

a <- (read)
b <- (read)
prn "sum: " a+b
prn "difference: " a-b
prn "product: " a*b
prn "quotient: " a/b
prn "integer quotient: " (int a/b)
prn "remainder: " a%b
prn "exponent: " a^b

Wren

In Wren the quotient operator '/' does not round but, when the floor method is applied to the result, it rounds to the lower integer.

The sign of the remainder operator '%' matches the sign of the first operand.

import "io" for Stdin, Stdout
System.write("first number:     ")
Stdout.flush()
var a = Num.fromString(Stdin.readLine())
System.write("second number:    ")
Stdout.flush()
var b = Num.fromString(Stdin.readLine())
System.print("sum:              %(a + b)")
System.print("difference:       %(a - b)")
System.print("product:          %(a * b)")
System.print("integer quotient: %((a / b).floor)")
System.print("remainder:        %(a % b)")
System.print("exponentiation:   %(a.pow(b))")
Output:

Sample input/output:

first number:     4
second number:    3
sum:              7
difference:       1
product:          12
integer quotient: 1
remainder:        1
exponentiation:   64

x86 Assembly

Input and output would be OS-specific and are not implemented. This routine works on the 16-bit 8086, as well as on its 32-bit and 64-bit successors: it could be trivially modified to perform 32-bit or 64-bit arithmetic on machines where those are supported. The quotient is truncated towards zero; the remainder takes its sign from the first operand.

arithm: mov      cx,          a
        mov      bx,          b
        xor      dx,          dx
        
        mov      ax,          cx
        add      ax,          bx
        mov      sum,         ax
        
        mov      ax,          cx
        imul     bx
        mov      product,     ax
        
        mov      ax,          cx
        sub      ax,          bx
        mov      difference,  ax
        
        mov      ax,          cx
        idiv     bx
        mov      quotient,    ax
        mov      remainder,   dx

        ret

XLISP

(DEFUN INTEGER-ARITHMETIC ()
    (DISPLAY "Enter two integers separated by a space.")
    (NEWLINE)
    (DISPLAY "> ")
    (DEFINE A (READ))
    (DEFINE B (READ))
    (DISPLAY `(SUM ,(+ A B)))
    (NEWLINE)
    (DISPLAY `(DIFFERENCE ,(- A B)))
    (NEWLINE)
    (DISPLAY `(PRODUCT ,(* A B)))
    (NEWLINE)
    (DISPLAY `(QUOTIENT ,(QUOTIENT A B))) ; truncates towards zero
    (NEWLINE)
    (DISPLAY `(REMAINDER ,(REM A B))) ; takes sign of first operand
    (NEWLINE)
    (DISPLAY `(EXPONENTIATION ,(EXPT A B))))

XPL0

include c:\cxpl\codes;
int A, B;
[A:= IntIn(0);
 B:= IntIn(0);
IntOut(0, A+B); CrLf(0);
IntOut(0, A-B); CrLf(0);
IntOut(0, A*B); CrLf(0);
IntOut(0, A/B); CrLf(0);        \truncates toward zero
IntOut(0, rem(0)); CrLf(0);     \remainder's sign matches first operand (A)
]

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>


Yabasic

input "ingrese un numero? " a
input "ingrese otro numero? " b

print "suma      ", a, " + ", b, " = ", (a + b)
print "resta     ", a, " - ", b, " = ", (a - b)
print "producto  ", a, " * ", b, " = ", (a * b)
print "division  ", a, " \ ", b, " = ", int(a / b)
print "modulo    ", a, " % ", b, " = ", mod(a, b)
print "potencia  ", a, " ^ ", b, " = ", (a ^ b)
end


Yorick

x = y = 0;
read, x, y;
write, "x + y =", x + y;
write, "x - y =", x - y;
write, "x * y =", x * y;
write, "x / y =", x / y; // rounds toward zero
write, "x % y =", x % y; // remainder; matches sign of first operand when operands' signs differ
write, "x ^ y =", x ^ y; // exponentiation

zkl

x,y:=ask("Two ints: ").split(" ").apply("toInt");
println("x+y = ",x + y);
println("x-y = ",x - y);
println("x*y = ",x * y);
println("x/y = ",x / y); // rounds toward zero
println("x%y = ",x % y); // remainder; matches sign of first operand when operands' signs differ
println("x.divr(y) = ",x.divr(y)); // (x/y,remainder); sign as above

zonnon

module Main;
var
	i,j: integer;
begin
	write("A integer?:");readln(i);
	write("another?: ");readln(j);
	writeln("sum: ",i + j);
	writeln("difference: ", i - j);
	writeln("product: ", i * j);
	writeln("quotient: ", i div j);
	writeln("remainder: ", i mod j);
end Main.
Output:
A integer?:2
another?: 3
sum:                    5
difference:                   -1
product:                    6
quotient:                    0
remainder:                    2

ZX Spectrum Basic

5 LET a=5: LET b=3
10 PRINT a;" + ";b;" = ";a+b
20 PRINT a;" - ";b;" = ";a-b
30 PRINT a;" * ";b;" = ";a*b
40 PRINT a;" / ";b;" = ";INT (a/b)
50 PRINT a;" mod ";b;" = ";a-INT (a/b)*b
60 PRINT a;" to the power of ";b;" = ";a^b