Anonymous user
Arithmetic/Integer: Difference between revisions
m
→{{header|Elena}}
imported>Arakov |
|||
(83 intermediate revisions by 51 users not shown) | |||
Line 1:
[[Category:Arithmetic operations]]
[[Category:Arithmetic]]
{{Task|Basic language learning}}
{{basic data operation}}
;Task:
Get two integers from the user, and then (for those two integers), display their:
Line 20:
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]]
=={{header|0815}}==
<
|~>|~#:end:>
<:61:x<:3d:=<:20:$==$~$=${~>%<:2c:~$<:20:~$
Line 36 ⟶ 38:
}:ml:x->{x{=>~*>{x<:1:-#:ter:^:ml:
}:ter:<:61:x<:5e:=<:20:$==$~$$=$<:62:x<:3D:=<:20:$==$~$=${{~%
</syntaxhighlight>
{{Out}}
<pre>
Line 50 ⟶ 52:
=={{header|11l}}==
<
V b = Int(input())
Line 58 ⟶ 60:
print(‘a / b = ’(a I/ b))
print(‘a % b = ’(a % b))
print(‘a ^ b = ’(a ^ b))</
=={{header|360 Assembly}}==
Line 76 ⟶ 78:
The sign of the quotient is determined by the rules of algebra.
The remainder has the same sign as the dividend.
<
ARITHINT CSECT
USING ARITHINT,R12
Line 114 ⟶ 116:
BUF DC CL12' '
YREGS
END ARITHINT</
Inputs are in the code: a=53, b=11
{{out}}
Line 127 ⟶ 129:
=={{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.
<
TXA
PHA
Line 174 ⟶ 176:
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.
=={{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 */
Line 305 ⟶ 332:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
{{
<PRE>
pi@debian-buster-64:~/asm64/rosetta/asm3 $ arith64 101 25
Line 315 ⟶ 342:
remainder :resultat : +1
</PRE>
=={{header|ABAP}}==
<
" Read in the two numbers from the user.
Line 340 ⟶ 368:
write: / 'Integer quotient:', lv_result. " Truncated towards zero.
lv_result = p_first mod p_second.
write: / 'Remainder:', lv_result.</
=={{header|ACL2}}==
<syntaxhighlight lang="lisp">
:set-state-ok t
Line 363 ⟶ 391:
(cw "Product: ~x0~%" (* a b))
(cw "Quotient: ~x0~%" (floor a b))
(cw "Remainder: ~x0~%" (mod a b))))))</
=={{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}}==
<
with Ada.Integer_Text_IO;
Line 385 ⟶ 465:
Put_Line("a**b = " & Integer'Image(A ** B));
end Integer_Arithmetic;</
=={{header|Aikido}}==
<
var b = 0
stdin -> a // read int from stdin
Line 397 ⟶ 477:
println ("a*b=" + (a * b))
println ("a/b=" + (a / b))
println ("a%b=" + (a % b))</
=={{header|ALGOL 68}}==
Line 404 ⟶ 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]}}
{{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}}
<
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))
)</
{{out}}
<pre>
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
</pre>
[[ALGOL 68R]] has
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).
INT quotient:=355, remainder;
remainder := quotient
=={{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.
<
integer a, b;
write( "Enter 2 integers> " );
Line 448 ⟶ 528:
% operand can be integer, real or complex ) %
write( "a ^ b: ", round( a ** b ) )
end.</
=={{header|AmigaE}}==
<
DEF a, b, t
WriteF('A = ')
Line 464 ⟶ 544:
WriteF('A*B=\d\nA/B=\d\n', Mul(a,b), Div(a,b))
WriteF('A mod B =\d\n', Mod(a,b))
ENDPROC</
=={{header|APL}}==
<
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 */
Line 766 ⟶ 866:
</syntaxhighlight>
=={{header|Arturo}}==
<
print [a
print [a
print [a
print [a
print [a
print [a
{{out}}
<pre>give me the first number : 33
give me the second number : 6
33 + 6 = 39
33 - 6 = 27
Line 792 ⟶ 890:
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}}==
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, vb, -3
Gui, Add, Button, Default, Compute
Line 813 ⟶ 931:
; fallthrough
GuiClose:
ExitApp</
=={{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}}==
<
print "add:", $1 + $2
print "sub:", $1 - $2
Line 823 ⟶ 956:
print "mod:", $1 % $2 # same sign as first operand
print "exp:", $1 ^ $2
exit }</
For division and modulus, Awk should act like C.
Line 833 ⟶ 966:
Same code as [[#Commodore_BASIC|Commodore BASIC]]
==={{header|BaCon}}===
<
DECLARE a%, b%
INPUT "Enter integer A: ", a%
Line 844 ⟶ 977:
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%))</
==={{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}}===
<
20 INPUT "ENTER ANOTHER NUMBER"; B%
30 PRINT "ADDITION:";A%;"+";B%;"=";A%+B%
Line 854 ⟶ 997:
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%</
==={{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}}===
<
! RosettaCode: Integer Arithmetic
! True BASIC v6.007
Line 872 ⟶ 1,081:
PRINT "POW(";a;", ";b;") is ";INT(a^b)
GET KEY done
END</syntaxhighlight>
==={{header|QBasic}}===
{{works with|QuickBasic|4.5}}
<
print a + b
print a - b
Line 882 ⟶ 1,091:
print a / b
print a mod b
end function</
Truncate towards: 0
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}}==
<syntaxhighlight lang="basic256">
input "enter a number ?", a
input "enter another number ?", b
Line 898 ⟶ 1,129:
print "remainder or modulo " + a + " % " + b + " = " + (a % b)
print "power " + a + " ^ " + b + " = " + (a ^ b)
</syntaxhighlight>
=={{header|Batch File}}==
{{works with|Windows
<
set /p equation=
set /
echo %result%
pause
</syntaxhighlight>
=={{header|BBC BASIC}}==
<
INPUT "Enter the second integer: " second%
Line 927 ⟶ 1,149:
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%</
=={{header|bc}}==
<
"add: "; a + b
"sub: "; a - b
Line 937 ⟶ 1,159:
"mod: "; a % b /* same sign as first operand */
"pow: "; a ^ b
}</
=={{header|Befunge}}==
<
v,+55.+g00:,,,,"A+B="<
>"=B-A",,,,:00g-.55+,v
v,+55.*g00:,,,,"A*B="<
>"=B/A",,,,:00g/.55+,v
@,+55.%g00,,,,"A%B="<</
=={{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}}==
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>.
<
= put$"Enter two integer numbers, separated by space:"
& get':(~/#?k_~/#?m|quit:?k)
Line 966 ⟶ 1,212:
& out$("Exponentiation:" !k^!m)
& done;
</syntaxhighlight>
=={{header|Brat}}==
Inspired by the second VBScript version.
<
y = ask("Second number: ").to_i
Line 976 ⟶ 1,222:
#Remainder uses sign of right hand side
[:+ :- :* :/ :% :^].each { op |
p "#{x} #{op} #{y} = #{x.call_method op, y}"</
=={{header|C}}==
<
#include <stdlib.h>
Line 995 ⟶ 1,241:
printf("a%%b = %d\n", a%b); /* same sign as first operand (in C99) */
return 0;
}</
=={{header|C sharp|C#}}==
<
class Program
Line 1,028 ⟶ 1,260:
Console.WriteLine("{0} to the power of {1} = {2}", a, b, Math.Pow(a, b));
}
}</
{{out}}
<pre>5 + 3 = 8
Line 1,036 ⟶ 1,268:
5 % 3 = 2
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}}==
<
Only reads single values.
Line 1,074 ⟶ 1,320:
Clean 1st mixing bowl.
Serves 5.</
=={{header|Clipper}}==
<
? "a+b", a + b
? "a-b", a - b
Line 1,087 ⟶ 1,333:
// Exponentiation is also a base arithmetic operation
? "a**b", a ** b
return</
=={{header|Clojure}}==
<
(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))))))</
<pre>user=> (myfunc)
Line 1,110 ⟶ 1,356:
=={{header|COBOL}}==
<
PROGRAM-ID. Int-Arithmetic.
Line 1,153 ⟶ 1,399:
GOBACK
.</
=={{header|Common Lisp}}==
<
(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 <code>floor</code>, <code>ceiling</code>, <code>truncate</code>, and <code>round</code>. They differ in how they round their quotient.
Line 1,188 ⟶ 1,434:
=={{header|Component Pascal}}==
Works with Gardens Point Component Pascal
<
MODULE Arithmetic;
IMPORT CPmain,Console,RTS;
Line 1,217 ⟶ 1,463:
Console.WriteString("x MOD y >");Console.WriteInt(x MOD y,6);Console.WriteLn;
END Arithmetic.
</syntaxhighlight>
command: <i>cprun Arithmetic 12 23</i><br/>
{{out}}
Line 1,228 ⟶ 1,474:
</pre>
Works with BlackBox Component Builder
<
MODULE Arithmetic;
IMPORT StdLog,DevCommanders,TextMappers;
Line 1,262 ⟶ 1,508:
END Go;
END Arithmetic.
</syntaxhighlight>
Command: Arithmetic.Go 12 23 ~ <br/>
{{out}}
Line 1,272 ⟶ 1,518:
x MOD y > 12
</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}}==
<
void main() {
Line 1,289 ⟶ 1,549:
writeln("a % b = ", a % b);
writeln("a ^^ b = ", a ^^ b);
}</
{{out}}
<pre>a = -16, b = 5
Line 1,301 ⟶ 1,561:
===Shorter Version===
Same output.
<
void main() {
Line 1,313 ⟶ 1,573:
foreach (op; AliasSeq!("+", "-", "*", "/", "%", "^^"))
mixin(`writeln("a ` ~ op ~ ` b = ", a` ~ op ~ `b);`);
}</
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}}==
<
Use whitespace to separate. Example: 2 3
Use underscore for negative integers. Example: _10
Line 1,326 ⟶ 1,606:
[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</
=={{header|DCL}}==
<
$ a = f$integer( a )
$ inquire b "Enter second number"
Line 1,335 ⟶ 1,616:
$ write sys$output "a - b = ", a - b
$ write sys$output "a * b = ", a * b
$ write sys$output "a / b = ", a / b ! truncates down</
{{out}}
<pre>$ @arithmetic_integer
Line 1,353 ⟶ 1,634:
=={{header|Delphi}}==
<
{$APPTYPE CONSOLE}
Line 1,371 ⟶ 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, Trunc(Power(a, b))]));
end.</
=={{header|DWScript}}==
<
var b := StrToInt(ParamStr(1));
Line 1,382 ⟶ 1,663:
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))]));</
=={{header|Dyalect}}==
Line 1,390 ⟶ 1,671:
Dyalect has no operator for exponential.
<
print("sum = \(a+b)")
print("difference = \(a-b)")
print("product = \(a*b)")
print("Integer quotient = \(a/b)")
print("Remainder = \(a%b)")</
=={{header|E}}==
<
return `$\
Sum: ${a + b}
Line 1,408 ⟶ 1,689:
Quotient: ${a // b}
Remainder: ${a % b}$\n`
}</
=={{header|EasyLang}}==
<syntaxhighlight lang="text">a = number input
b = number input
print a + b
print a - b
print a * b
print a
print a mod b
print pow a b</syntaxhighlight>
=={{header|ECL}}==
<syntaxhighlight lang="ecl">
ArithmeticDemo(INTEGER A,INTEGER B) := FUNCTION
ADDit := A + B;
Line 1,453 ⟶ 1,735:
This default behavior can be changed
*/
</syntaxhighlight>
=={{header|Efene}}==
<
run = fn () {
Line 1,471 ⟶ 1,753:
io.format("Quotient: ~p~n", [A / B])
io.format("Remainder: ~p~n", [A % B])
}</
=={{header|Eiffel}}==
{{works with|SmartEiffel|2.4}}
In a file called main.e:
<
creation make
feature make is
Line 1,504 ⟶ 1,786:
print("%N");
end
end</
Note that there actually is a builtin modulo operator (\\). However, it seems impossible to use that instruction with SmartEiffel.
=={{header|Elena}}==
ELENA
<
import extensions;
Line 1,521 ⟶ 1,803:
console.printLine(a," * ",b," = ",a * b);
console.printLine(a," / ",b," = ",a / b); // truncates towards 0
console.printLine(a," % ",b," = ",a.mod
console.printLine(a," ^ ",b," = ",a ^ b);
}</syntaxhighlight>
=={{header|Elixir}}==
{{works with|Elixir|1.4}}
<
# Function to remove line breaks and convert string to int
defp get_int(msg) do
Line 1,550 ⟶ 1,833:
end
Arithmetic_Integer.task</
{{out}}
Line 1,614 ⟶ 1,897:
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}}==
<
-module(arith).
-export([start/0]).
Line 1,630 ⟶ 1,972:
halt()
end.
</syntaxhighlight>
=={{header|ERRE}}==
<syntaxhighlight lang="text">
PROGRAM INTEGER_ARITHMETIC
Line 1,653 ⟶ 1,995:
PRINT("Power ";A;"^";B;"=";(A^B))
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>Enter a number ? 12
Line 1,671 ⟶ 2,013:
=={{header|Euphoria}}==
<
integer a,b
Line 1,683 ⟶ 2,025:
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))</
{{out}}
Line 1,700 ⟶ 2,042:
For sum, type in C1
<
=$A1+$B1
</syntaxhighlight>
For difference, type in D1
<
=$A1-$B1
</syntaxhighlight>
For product, type in E1
<
=$A1*$B1
</syntaxhighlight>
For quotient, type in F1
<
=QUOTIENT($A1,$B1)
</syntaxhighlight>
For remainder, type in G1
<
=MOD($A1,$B1)
</syntaxhighlight>
For exponentiation, type in H1
<
=$A1^$B1
</syntaxhighlight>
=={{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}}==
<
math.parser prettyprint ;
Line 1,746 ⟶ 2,105:
[ gcd "gcd: " write . drop ]
[ lcm "lcm: " write . ]
} 2cleave</
{{out}}
Line 1,767 ⟶ 2,126:
=={{header|FALSE}}==
<
\$@$@$@$@$@$@$@$@$@$@\ { 6 copies }
"sum = "+."
Line 1,774 ⟶ 2,133:
quotient = "/."
modulus = "/*-."
"</
=={{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}}==
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 ).
<
cr ." a=" over . ." b=" dup .
cr ." a+b=" 2dup + .
Line 1,784 ⟶ 2,166:
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.
<
SM/REM ( d n -- rem div ) \ symmetric
M* ( n n -- d )</
In addition, there are unsigned variants.
<
UM* ( u u -- ud )</
=={{header|Fortran}}==
In ANSI FORTRAN 77 or later:
<
PRINT *, 'Type in two integer numbers separated by white space',
+ ' and press ENTER'
Line 1,812 ⟶ 2,194:
+ 'exponentiation is an intrinsic op in Fortran, so...'
PRINT *, ' A ** B = ', (A ** B)
END</
=={{header|FreeBASIC}}==
<
Dim As Integer i, j
Line 1,830 ⟶ 2,212:
' Remainder (for which FB uses the Mod operator) will, if non-zero, match the sign
' of the first operand</
Sample input and output:-
Line 1,843 ⟶ 2,225:
-12 ^ 7 = -35831808
</pre>
=={{header|friendly interactive shell}}==
<
read a
read b
Line 1,872 ⟶ 2,236:
echo 'a % b =' (math "$a % $b") # Remainder
echo 'a ^ b =' (math "$a ^ $b") # Exponentation
</syntaxhighlight>
=={{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.
<
[a,b] = input["Enter numbers",["a","b"]]
ops=["+", "-", "*", "/", "div" ,"mod" ,"^"]
Line 1,884 ⟶ 2,248:
println["$str = " + eval[str]]
}
</syntaxhighlight>
{{out}}
<
10 + 20 = 30
10 - 20 = -10
Line 1,895 ⟶ 2,259:
10 mod 20 = 10
10 ^ 20 = 100000000000000000000
</syntaxhighlight>
=={{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>
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
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}}==
<
local a, b, f;
f := InputTextUser();
Line 1,959 ⟶ 2,468:
Display(Concatenation(String(a), " ^ ", String(b), " = ", String(a ^ b)));
CloseStream(f);
end;</
=={{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.
<
/*
Arithmethic/Integer, in Genie
Line 1,984 ⟶ 2,528:
print "\nGenie does not include a raise to power operator"
return 0</
{{out}}
Line 1,998 ⟶ 2,542:
=={{header|GEORGE}}==
<
R (n) ;
m n + P;
Line 2,004 ⟶ 2,548:
m n × P;
m n div P;
m n rem P;</
=={{header|Go}}==
===int===
<
import "fmt"
Line 2,022 ⟶ 2,566:
fmt.Printf("%d %% %d = %d\n", a, b, a%b) // same sign as first operand
// no exponentiation operator
}</
{{out|Example run}}
<pre>
Line 2,033 ⟶ 2,577:
</pre>
===big.Int===
<
import (
Line 2,061 ⟶ 2,605:
// as with int, no exponentiation operator
}</
{{out|Example run}}
<pre>
Line 2,073 ⟶ 2,617:
-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}}==
'''Solution:'''
<
println """
a + b = ${a} + ${b} = ${a + b}
Line 2,089 ⟶ 2,637:
a ** b = ${a} ** ${b} = ${a ** b}
"""
}</
'''Test:'''
<syntaxhighlight lang
{{out}}
Line 2,107 ⟶ 2,655:
=={{header|Harbour}}==
<
? "a+b", a + b
? "a-b", a - b
Line 2,117 ⟶ 2,665:
// Exponentiation is also a base arithmetic operation
? "a**b", a ** b
return</
=={{header|Haskell}}==
<
a <- readLn :: IO Integer
b <- readLn :: IO Integer
Line 2,135 ⟶ 2,683:
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)</
=={{header|Haxe}}==
<
public static function main() {
var args =Sys.args();
Line 2,150 ⟶ 2,698:
trace("a%b = " + (a%b));
}
}</
=={{header|HicEst}}==
All numeric is 8-byte-float. Conversions are by INT, NINT, FLOOR, CEILING, or Formatted IO
<
WRITE(Name) A, B
WRITE() ' A + B = ', A + B
Line 2,166 ⟶ 2,714:
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 + B = 1
A - B = 9
Line 2,178 ⟶ 2,726:
remainder of A / B = 1
A to the power of B = 16E-4
A to the power of B = 16E-4 </
=={{header|HolyC}}==
<
a = Str2I64(GetStr("Enter your first number: "));
b = Str2I64(GetStr("Enter your second number: "));
Line 2,194 ⟶ 2,742:
Print("a % b = %d\n", a % b); /* same sign as first operand */
Print("a ` b = %d\n", a ` b);
}</
=={{header|i}}==
<
a $= integer(in(' ')); ignore
b $= integer(in('\n')); ignore
Line 2,207 ⟶ 2,755:
print("Modulus:" , a % b) // same sign as first operand
print("Exponent:" , a ^ b)
}</
=={{header|Icon}} and {{header|Unicon}}==
<
writes("Input 1st integer a := ")
a := integer(read())
Line 2,222 ⟶ 2,770:
write(" a % b = ",a%b, " remainder sign matches a")
write(" a ^ b = ",a^b)
end</
=={{header|Inform 7}}==
<
Numerically entering is an action applying to one number. Understand "[number]" as numerically entering.
Line 2,249 ⟶ 2,797:
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.
=={{header|J}}==
<
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.
<
20 14 51 5 2 4913</
The function <code>bia</code> assembles these results, textually:
<
combine =: ,. ":@,.
bia =: labels combine calc
Line 2,271 ⟶ 2,819:
Quotient: 5
Remainder: 2
Exponentiation: 4913</
=={{header|Java}}==
<
public class IntegerArithmetic {
Line 2,295 ⟶ 2,843:
System.out.println("remainder of a / b = " + remainder); // same sign as first operand
}
}</
=={{header|JavaScript}}==
Line 2,302 ⟶ 2,850:
{{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 b = parseInt(get_input("Enter an integer"), 10);
Line 2,327 ⟶ 2,875:
print(prompt);
}
}</
{{out}}
<pre>Enter an integer
Line 2,341 ⟶ 2,889:
remainder: a % b = -21</pre>
===Node.JS===
<
var a = parseInt(process.argv[2], 10);
var b = parseInt(process.argv[3], 10);
Line 2,355 ⟶ 2,903:
console.log('a * b = %d', product);
console.log('a / b = %d', division);
console.log('a % b = %d', remainder);</
{{out}}
<pre>
a + b = 17
a - b = 3
a * b = 70
Line 2,364 ⟶ 2,913:
=={{header|jq}}==
<
def arithmetic:
Line 2,381 ⟶ 2,930:
arithmetic
</syntaxhighlight>
{{Out}}
<pre>
Line 2,413 ⟶ 2,962:
=={{header|Jsish}}==
<
/* Arthimetic/Integer, in Jsish */
var line = console.input();
Line 2,445 ⟶ 2,994:
Exponentiation A to the power B is 2401
=!EXPECTEND!=
*/</
{{out}}
Line 2,452 ⟶ 3,001:
=={{header|Julia}}==
<
for op in [+,-,*,div,rem]
println("a $op b = $(op(a,b))")
end
end</
{{Out}}
<pre>julia> arithmetic()
Line 2,468 ⟶ 3,017:
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">
import kotlin.math.pow // not an operator but in the standard library
fun main(
val r = Regex("""-?
print("Enter two integers separated by space(s): ")
val input: String = readLine()!!.trim()
val a = input.substring(0, index).trimEnd().toLong()
val b = input.substring(index
println("$a + $b = ${a + b}")
println("$a - $b = ${a -
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 ^
}
}</syntaxhighlight>
{{out}}
<pre>
Enter two integers separated by space(s)
2 + 63 = 65
2 - 63 = -61
Line 2,518 ⟶ 3,044:
2 / 63 = 0
2 % 63 = 2
2 ^ 63 =
</pre>
Line 2,535 ⟶ 3,051:
[[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}}==
<
#a + #b // 10
#a - #b // 2
Line 2,545 ⟶ 3,084:
#a % #b // 2
math_pow(#a,#b) // 1296
math_pow(#b,#a) // 4096</
=={{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}}==
<
(defmodule arith
(export all))
Line 2,564 ⟶ 3,139:
; rem's result takes the same sign as the first operand
(: io format '"~p rem ~p = ~p~n" (list a b (rem a b))))))
</syntaxhighlight>
Usage from the LFE REPL:
<
> (slurp '"arith.lfe")
#(ok arith)
Line 2,579 ⟶ 3,154:
2 rem 8 = 2
ok
</syntaxhighlight>
=={{header|Liberty BASIC}}==
Note that raising to a power can display very large integers without going to approximate power-of-ten notation.
<syntaxhighlight lang="lb">
input "Enter the first integer: "; first
input "Enter the second integer: "; second
Line 2,593 ⟶ 3,168:
print "The remainder is " ; first MOD second; " (sign matches first operand)"
print "The first raised to the power of the second is " ; first ^second
</syntaxhighlight>
=={{header|LIL}}==
<
write "Enter two numbers separated by space: "
if {[canread]} {set line [readline]}
Line 2,609 ⟶ 3,184:
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"</
{{out}}
Line 2,633 ⟶ 3,208:
=={{header|Lingo}}==
<
x = integer(member("X").text)
y = integer(member("Y").text)
Line 2,642 ⟶ 3,217:
put "Quotient: " , x / y -- Truncated towards zero
put "Remainder: " , x mod y -- Result has sign of left operand
put "Exponent: " , power(x, y)</
=={{header|Little}}==
<
# from Tcl with:
# eval("namespace path ::tcl::mathfunc");
Line 2,659 ⟶ 3,234:
puts("${a} / ${b} = ${a/b}, remainder ${a%b}");
puts("${a} to the power of ${b} = ${(int)pow(a,b)}");
}</
=={{header|LiveCode}}==
<
if it is not empty then
put item 1 of it into n1
Line 2,673 ⟶ 3,248:
combine ai using comma and colon
put ai
end if</
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</
=={{header|Logo}}==
<
(print [a =] :a)
(print [b =] :b)
Line 2,689 ⟶ 3,264:
(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.
=={{header|LSE64}}==
<
2dup : over over
Line 2,703 ⟶ 3,278:
" A*B=" ,t 2dup * , nl \
" A/B=" ,t 2dup / , nl \
" A%B=" ,t % , nl</
=={{header|Lua}}==
<
local y = io.read()
Line 2,714 ⟶ 3,289:
print ("Quotient: " , (x / y)) -- Does not truncate
print ("Remainder: " , (x % y)) -- Result has sign of right operand
print ("Exponent: " , (x ^ y))</
=={{header|M2000 Interpreter}}==
Line 2,722 ⟶ 3,297:
<syntaxhighlight lang="m2000 interpreter">
MODULE LikeCommodoreBasic {
\\ ADDITION: EUCLIDEAN DIV# & MOD# AND ** FOR POWER INCLUDING ^
Line 2,770 ⟶ 3,345:
}
IntegerTypes
</syntaxhighlight>
=={{header|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)</
once saved in a file, e.g. <tt>operations.m4</tt>:
Line 2,787 ⟶ 3,362:
or using a sort of ''driver'':
<
define(`B', 6)dnl
include(`operations.m4')</
=={{header|Maple}}==
These operations are all built-in. As all operations are exact, there are no rounding issues involved.
<syntaxhighlight lang="maple">
DoIt := proc()
local a := readstat( "Input an integer: " ):
Line 2,804 ⟶ 3,379:
NULL # quiet return
end proc:
</syntaxhighlight>
Here is an example of calling DoIt.
<syntaxhighlight lang="maple">
> DoIt();
Input an integer: 15;
Line 2,816 ⟶ 3,391:
Remainder = 3
>
</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Mathematica has all the function built-in to handle this task. Example:
<
b = Input["Give me another integer please!"];
Print["You gave me ", a, " and ", b];
Line 2,826 ⟶ 3,401:
Print["difference: ", a - b];
Print["product: ", a b];
Print["integer quotient: ",
Print["remainder: ", Mod[a, b]];
Print["exponentiation: ", a^b];</
gives back for input 17 and 3:
<
sum: 20
difference: 14
Line 2,837 ⟶ 3,412:
remainder: 2
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}}==
<
disp("integer b: "); b = scanf("%d", 1);
a+b
Line 2,846 ⟶ 3,474:
floor(a/b)
mod(a,b)
a^b</
=={{header|Maxima}}==
<
[a: read("a"), b: read("b")],
print(a + b),
Line 2,858 ⟶ 3,486:
print(remainder(a, b)),
a^b
);</
=={{header|MAXScript}}==
<
y = getKBValue prompt:"Second number:"
Line 2,868 ⟶ 3,496:
format "Product: %\n" (x * y)
format "Quotient: %\n" (x / y)
format "Remainder: %\n" (mod x y)</
=={{header|Mercury}}==
<syntaxhighlight lang="text">
:- module arith_int.
:- interface.
Line 2,914 ⟶ 3,542:
io.set_exit_status(1, !IO)
).
</syntaxhighlight>
=={{header|Metafont}}==
<
message "input number a: ";
s1 := readstring;
Line 2,935 ⟶ 3,563:
outp("mod");
end</
=={{header|min}}==
{{works with|min|0.
<syntaxhighlight lang="min">('+ '- '* 'div 'mod)
(("Enter an integer" ask integer) 2 times) quote-map =>
("
map "\n" join puts!</syntaxhighlight>
{{out}}
<pre>
Line 2,955 ⟶ 3,583:
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">П1 <-> П0
+ С/П
ИП0 ИП1 - С/П
Line 2,961 ⟶ 3,589:
ИП0 ИП1 / [x] С/П
ИП0 ^ ИП1 / [x] ИП1 * - С/П
ИП1 ИП0 x^y С/П</
=={{header|ML/I}}==
Line 2,967 ⟶ 3,595:
and then output the results to 'standard output' or similar.
<
"" Arithmetic/Integer
"" assumes macros on input stream 1, terminal on stream 2
Line 2,981 ⟶ 3,609:
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.</
=={{header|Modula-2}}==
<
IMPORT InOut;
Line 3,000 ⟶ 3,628:
InOut.WriteString ("a MOD b = "); InOut.WriteInt (a MOD b, 9); InOut.WriteLn;
InOut.WriteLn;
END ints.</
Enter two integer numbers : 12 7
a + b = 19
Line 3,017 ⟶ 3,645:
=={{header|Modula-3}}==
<
IMPORT IO, Fmt;
Line 3,031 ⟶ 3,659:
IO.Put("a DIV b = " & Fmt.Int(a DIV b) & "\n");
IO.Put("a MOD b = " & Fmt.Int(a MOD b) & "\n");
END Arith.</
=={{header|MUMPS}}==
Line 3,042 ⟶ 3,670:
find out the beauty of cyclic algebra as formulated by Niels Henrik Abel (August 5, 1802 – April 6, 1829).</p>
<
Write "Plus",?12,first,"+",second,?25," = ",first+second,!
Write "Minus",?12,first,"-",second,?25," = ",first-second,!
Line 3,085 ⟶ 3,713:
Modulo 0#2 = 0
And 0&2 = 0
Or 0!2 = 1</
=={{header|Nanoquery}}==
{{trans|Python}}
<
x = int(input())
print "Number 2: "
Line 3,101 ⟶ 3,728:
println format("Remainder: %d", x % y)
println format("Power: %d", x ^ y)</
{{out}}
Line 3,112 ⟶ 3,739:
Remainder: 5
Power: 15625</pre>
=={{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.
<
class Program
Line 3,132 ⟶ 3,758:
Console.WriteLine("{0} ** {1} = {2}", a, b, a ** b);
}
}</
=={{header|NetRexx}}==
{{trans|REXX}}
<
options replace format comments java crossref symbols binary
Line 3,149 ⟶ 3,775:
return
</syntaxhighlight>
{{out}}
<pre style="height: 15ex; overflow:scroll;">
Line 3,163 ⟶ 3,789:
=={{header|NewLISP}}==
<
; oofoe 2012-01-17
Line 3,187 ⟶ 3,813:
(exit) ; NewLisp normally goes to listener after running script.
</syntaxhighlight>
{{out}}
Line 3,209 ⟶ 3,835:
Define new operator using an atlas of operators:
<
Test new operator:
<
-23 7 -16 -30 -161 -4 5 -3404825447</
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>.
Line 3,225 ⟶ 3,851:
Nial definition of <code>quotient</code>:
<
<code>floor</code> rounds towards negative infinity (next lower integer).
=={{header|Nim}}==
<syntaxhighlight lang="nim">import parseopt, strutils
var
Line 3,252 ⟶ 3,876:
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))
</syntaxhighlight>
Execute: Aritmint 4 5
{{out}}
<pre>
a :
b :
a + b :
a - b : -
a * b :
a div b:
a mod b:
a ^ b : 1024
</pre>
=={{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.
<
Push $0
Push $1
Line 3,292 ⟶ 3,918:
Pop $1
Pop $0
FunctionEnd</
=={{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}}==
Oxford Oberon-2
<
MODULE Arithmetic;
IMPORT In, Out;
Line 3,309 ⟶ 3,979:
Out.String("x MOD y >");Out.Int(x MOD y,6);Out.Ln;
END Arithmetic.
</syntaxhighlight>
{{out}}
<pre>
Line 3,319 ⟶ 3,989:
x MOD y > 12
</pre>
=={{header|Objeck}}==
<
class Arithmetic {
function : Main(args : System.String[]) ~ Nil {
Line 3,336 ⟶ 4,007:
}
}
}</
=={{header|OCaml}}==
<
let a = read_int ()
and b = read_int () in
Line 3,347 ⟶ 4,018:
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 *)</
=={{header|Oforth}}==
<
"a + b =" . a b + .cr
"a - b =" . a b - .cr
Line 3,358 ⟶ 4,029:
"a mod b =" . a b mod .cr
"a pow b =" . a b pow .cr
;</
{{out}}
Line 3,374 ⟶ 4,045:
=={{header|Ol}}==
<
(define a 8)
(define b 12)
Line 3,387 ⟶ 4,058:
(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>
Line 3,400 ⟶ 4,078:
(modulo 8 12) => 8
(expt 8 12) => 68719476736
(gcd 8 12) => 4
(lcm 8 12) => 24
25
-23
945
1/945
</pre>
=={{header|Onyx}}==
<
# All you really need to do is push two integers onto the stack
# and then execute add, sub, mul, idiv, or pow.
Line 3,455 ⟶ 4,130:
} bind def
ClearScreen ShowPreamble $A GetInt $B GetInt ShowResults</
{{out}}
Line 3,476 ⟶ 4,151:
=={{header|Openscad}}==
<
echo (a-b); /* Difference */
echo (a*b); /* Product */
echo (a/b); /* Quotient */
echo (a%b); /* Modulus */</
=={{header|Oz}}==
<
StdIn = {New class $ from Open.file Open.text end init(name:stdin)}
Line 3,501 ⟶ 4,176:
"A^B = "#{Pow A B}
]
System.showInfo}</
=={{header|Panda}}==
Use reflection to get all functions defined on numbers taking number and returning number.
<
{{out}}
Line 3,531 ⟶ 4,195:
plus ( 3 7 ) => 10
pow ( 3 7 ) => 2187</pre>
=={{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.
<syntaxhighlight lang="parigp">arith(a,b)={
print(a+b);
print(a-b);
print(a*b);
print(a\b);
print(a%b);
print(a^b);
};</syntaxhighlight>
=={{header|Pascal}}==
<
var
Line 3,544 ⟶ 4,219:
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.</syntaxhighlight>
=={{header|Perl}}==
{{works with|Perl|5.x}}
<
my $b = <>;
Line 3,558 ⟶ 4,235:
"remainder: ", $a % $b, "\n",
"exponent: ", $a ** $b, "\n"
;</
=={{header|Phix}}==
{{libheader|Phix/pGUI}}
{{libheader|Phix/online}}
You can run this online [http://phix.x10.mx/p2js/ArithInt.htm here] (layout/space is not perfected yet).
<!--<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
Line 3,592 ⟶ 4,295:
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}}==
<syntaxhighlight lang="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</syntaxhighlight>
=={{header|PHL}}==
<
extern printf;
Line 3,617 ⟶ 4,336:
return 0;
]</
=={{header|PHP}}==
<
$a = fgets(STDIN);
$b = fgets(STDIN);
Line 3,632 ⟶ 4,351:
"remainder: ", $a % $b, "\n",
"power: ", $a ** $b, "\n"; // PHP 5.6+ only
?></
=={{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}}==
<
(prinl "Add " (+ A B))
(prinl "Subtract " (- A B))
Line 3,642 ⟶ 4,381:
(prinl "Div/rnd " (*/ A B)) # Rounds to next integer
(prinl "Modulus " (% A B)) # Sign of the first operand
(prinl "Power " (** A B)) )</
=={{header|Piet}}==
[[File:PietArithmaticInteger.png]]<br>
Line 3,684 ⟶ 4,424:
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
get list (a, b);
put skip list (a+b);
Line 3,691 ⟶ 4,431:
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. */</
=={{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}}==
<
vars itemrep;
incharitem(charin) -> itemrep;
Line 3,705 ⟶ 4,484:
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');</
=={{header|PostScript}}==
<
/x exch def
/y exch def
Line 3,717 ⟶ 4,496:
x y mod =
x y exp =
} def</
=={{header|PowerShell}}==
<
$b = [int] (Read-Host Second Number)
Line 3,727 ⟶ 4,507:
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.
Line 3,733 ⟶ 4,513:
No exponentiation operator exists, but can be worked around with the .NET BCL:
<
=={{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}}==
<
include arithmeticmodule
:a
Line 3,753 ⟶ 4,549:
editvar /newvar /value=d /title=Do you want to calculate more numbers?
if -d- /hasvalue yes goto :a else goto :end
:end</
<
:a
editvar /newvar /value=a /title=Enter first integer:
Line 3,769 ⟶ 4,565:
editvar /newvar /value=d /title=Do you want to calculate more numbers?
if -d- /hasvalue yes goto :a else goto :end
:end</
=={{header|Prolog}}==
Line 3,777 ⟶ 4,573:
Remainder (`rem`) matches the sign of its first operand.
<
print_expression_and_result(M, N, Operator) :-
Line 3,789 ⟶ 4,585:
maplist( print_expression_and_result(M, N), [+,-,*,//,rem,^] ).
</syntaxhighlight>
Use thus:
<
?- arithmetic_integer.
|: 5.
Line 3,804 ⟶ 4,600:
5^7 is 78125
true.
</syntaxhighlight>
=={{header|PureBasic}}==
<
Define a, b
Line 3,823 ⟶ 4,619:
Input()
CloseConsole()</
=={{header|Python}}==
<
y = int(raw_input("Number 2: "))
Line 3,840 ⟶ 4,636:
## 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:
<
while True: # retrying ...
try:
Line 3,856 ⟶ 4,652:
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).
Line 3,865 ⟶ 4,661:
=== Python 3.0 compatible code ===
<
for op in "+ - * // % **".split():
expr = "%(x)s %(op)s %(y)s" % vars()
Line 3,872 ⟶ 4,668:
arithmetic(12, 8)
arithmetic(input("Number 1: "), input("Number 2: "))</
{{out}}
<pre>12 + 8 => 20
Line 3,888 ⟶ 4,684:
20 % 4 => 0
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
<
INPUT "Enter two integers (a,b):"; a!, b!
IF a = 0 THEN END
Line 3,910 ⟶ 4,739:
IF UCASE$(a$) = "Y" THEN CLS: GOTO START
CLS
END</
=={{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}}==
<
a <- scan(nmax=1, quiet=TRUE)
cat("insert number ")
Line 3,923 ⟶ 4,777:
print(paste('a%%b=', a%%b))
print(paste('a^b=', a^b))
</syntaxhighlight>
=={{header|Racket}}==
<
#lang racket/base
Line 3,934 ⟶ 4,788:
(arithmetic 8 12)
</syntaxhighlight>
{{out}}
<pre>
Line 3,949 ⟶ 4,803:
(lcm 8 12) => 24
</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}}==
<
' Number 2: ' print expect 0 prefer as y
Line 3,959 ⟶ 4,827:
x y * " product: %d\n" print
x y / " quotient: %d\n" print
x y % " remainder: %d\n" print</
=={{header|REBOL}}==
<
Title: "Integer"
URL: http://rosettacode.org/wiki/Arithmetic/Integer
Line 4,012 ⟶ 4,880:
]
print ["Exponentiation:" x ** y]</
{{out}}
Line 4,031 ⟶ 4,899:
Remainder sign matches: first
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}}==
Retro's arithmetic functions are based on those in [[Forth]]. The example is an adaption of the one from Forth.
<
over '\na_______=_%n s:put
dup '\nb_______=_%n s:put
Line 4,042 ⟶ 4,951:
dup-pair * '\na_*_b___=_%n s:put
/mod '\na_/_b___=_%n s:put
'\na_mod_b_=_%n\n" s:put ;</
=={{header|REXX}}==
All operators automatically produce integers where appropriate (up to twenty decimal digits in the program below),
<br>or numbers in exponential format when necessary. (The REXX default is
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 (in the example program below, it is
<
numeric digits 20 /*#s are round at 20th significant dig.*/
parse arg x y . /*maybe the integers are on the C.L. */
Line 4,073 ⟶ 4,982:
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</
{{out|output|text= when using the input of: <tt> 4 -17 </tt>}}
<pre>
Line 4,094 ⟶ 5,003:
=={{header|Ring}}==
<
func Test a,b
see "a+b" + ( a + b ) + nl
Line 4,104 ⟶ 5,013:
see "a%b" + ( a % b ) + nl
see "a**b" + pow(a,b ) + nl
</syntaxhighlight>
=={{header|Robotic}}==
<
input string "Enter number 1:"
set "a" to "input"
Line 4,119 ⟶ 5,028:
[ "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>
=={{header|Ruby}}==
<
x = gets.to_i # to check errors, use x=Integer(gets)
y = gets.to_i
Line 4,133 ⟶ 5,062:
"Quotient: #{x.fdiv(y)}", # float
"Remainder: #{x%y}", # same sign as second operand
"Exponentiation: #{x**y}"
"Quotient: %d with Remainder: %d" % x.divmod(y)</syntaxhighlight>
=={{header|Run BASIC}}==
<
input "2nd integer: "; i2
Line 4,144 ⟶ 5,074:
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</
=={{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.
<
fn main() {
Line 4,161 ⟶ 5,091:
println!("integer quotient: {}", a / b); // truncates towards zero
println!("remainder: {}", a % b); // same sign as first operand
}</
=={{header|Sass/SCSS}}==
<
@function arithmetic($a,$b) {
@return $a + $b, $a - $b, $a * $b, ($a - ($a % $b))/$b, $a % $b;
}
</syntaxhighlight>
Which you use with:
<
nth(arithmetic(10,3),1);
</syntaxhighlight>
Or each of the functions separately:
<
@function sum($a,$b) {
@return $a + $b;
Line 4,199 ⟶ 5,129:
@return $a / $b;
}
</syntaxhighlight>
=={{header|Scala}}==
<
val b = Console.readInt
Line 4,210 ⟶ 5,140:
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</
=={{header|Scheme}}==
<
(for-each (lambda (op)
(write (list op x y))
Line 4,222 ⟶ 5,152:
'(+ - * / quotient remainder modulo max min gcd lcm)))
(arithmetic 8 12)</
quotient - truncates towards 0
remainder - same sign as first operand
Line 4,242 ⟶ 5,172:
=={{header|Seed7}}==
<
const proc: main is func
Line 4,261 ⟶ 5,191:
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;</
=={{header|SenseTalk}}==
<
put it into number1
Line 4,275 ⟶ 5,205:
put "Integer quotient: " & number1 div number2 -- Rounding towards 0
put "Remainder: " & number1 rem number2
put "Exponentiation: " & number1 to the power of number2</
=={{header|Sidef}}==
<
var b = Sys.scanln("Second number: ").to_i;
%w'+ - * // % ** ^ | & << >>'.each { |op|
"#{a} #{op} #{b} = #{a.$op(b)}".say;
}</
{{out}}
Line 4,303 ⟶ 5,233:
=={{header|Slate}}==
<
inform: (a + b) printString.
inform: (a - b) printString.
Line 4,311 ⟶ 5,241:
inform: (a \\ b) printString.
] applyTo: {Integer readFrom: (query: 'Enter a: '). Integer readFrom: (query: 'Enter b: ')}.</
=={{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}}==
{{works with|GNU Smalltalk}}
<
'Input number a: ' display.
a := (stdin nextLine) asInteger.
Line 4,324 ⟶ 5,267:
('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)
<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}}==
<
INPUT "Enter second number.":second
PRINT "The sum of";first;"and";second;"is ";first+second&"."
Line 4,338 ⟶ 5,339:
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:
Line 4,347 ⟶ 5,348:
=={{header|SNOBOL4}}==
<
output = "Enter first integer:"
first = input
Line 4,357 ⟶ 5,358:
output = "quot = " (qout = first / second)
output = "rem = " first - (qout * second)
output = "expo = " first ** second
end</syntaxhighlight>
=={{header|SNUSP}}==
Line 4,363 ⟶ 5,365:
''See also: [[Ethiopian Multiplication]]''
<syntaxhighlight lang="snusp">$\
,
@
Line 4,420 ⟶ 5,422:
\=@@@+@+++++#
.
#</
=={{header|SQL}}==
{{works with|Oracle}}
<
-- test.sql
-- Tested in SQL*plus
Line 4,445 ⟶ 5,447:
select power(a,b) exponentiation from test;
</syntaxhighlight>
<pre>
Line 4,494 ⟶ 5,496:
=={{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.
<
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 (<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.
<
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]].
=={{header|Standard ML}}==
<
val a = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn)))
val b = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn)))
Line 4,522 ⟶ 5,524:
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</
=={{header|Swift}}==
<
let a = 6
let b = 4
Line 4,534 ⟶ 5,537:
print("Remainder = (a%b)")
print("No operator for Exponential")
</syntaxhighlight>
=={{header|Tcl}}==
<
set x [expr {int([gets stdin])}]; # Force integer interpretation
Line 4,547 ⟶ 5,550:
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 "<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 stdin])</tt>.
Line 4,553 ⟶ 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
<syntaxhighlight lang
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}}==
Pauses added due to TI-83's lack of screen size.
<
Prompt A,B
Disp "SUM"
Line 4,571 ⟶ 5,633:
Disp "REMAINDER"
Pause A-B*int(A/B)
</syntaxhighlight>
=={{header|TI-89 BASIC}}==
<
Prompt a, b
Disp "Sum: " & string(a + b)
Line 4,581 ⟶ 5,643:
Disp "Product: " & string(a * b)
Disp "Integer quotient: " & string(intDiv(a, b))
Disp "Remainder: " & string(remain(a, b))</
=={{header|Toka}}==
<
2dup ." a+b = " + . cr
2dup ." a-b = " - . cr
2dup ." a*b = " * . cr
2dup ." a/b = " / . ." remainder " mod . cr
] is mathops</
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
a=5
Line 4,602 ⟶ 5,664:
c=a/b
c=a%b
</syntaxhighlight>
{{out}}
<pre>
Line 4,625 ⟶ 5,687:
{{works with|Bourne Shell}}
{{works with|Almquist SHell}}
<
read a; read b;
echo "a+b = " `expr $a + $b`
Line 4,631 ⟶ 5,693:
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.
Line 4,640 ⟶ 5,702:
{{works with|pdksh|5.2.14}}
{{works with|Z SHell}}
<
read a; read b;
echo "a+b = $((a+b))"
Line 4,646 ⟶ 5,708:
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.
=={{header|Ursa}}==
<
# integer arithmetic
#
Line 4,667 ⟶ 5,729:
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:
Line 4,680 ⟶ 5,742:
=={{header|VBA}}==
<syntaxhighlight lang="vb">
'Arithmetic - Integer
Sub RosettaArithmeticInt()
Line 4,698 ⟶ 5,760:
Next opr
End Sub
</syntaxhighlight>
=={{header|VBScript}}==
Line 4,704 ⟶ 5,766:
===Implementation===
<
dim a, b
wscript.stdout.write "A? "
Line 4,720 ⟶ 5,782:
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.
<
dim a, b
wscript.stdout.write "A? "
Line 4,737 ⟶ 5,799:
for each op in split("+ - * / \ mod ^", " ")
wscript.echo "a",op,"b=",eval( "a " & op & " b")
next</
===Invocation===
Line 4,754 ⟶ 5,816:
=={{header|Vedit macro language}}==
<
#2 = Get_Num("Give number b: ")
Message("a + b = ") Num_Type(#1 + #2)
Line 4,760 ⟶ 5,822:
Message("a * b = ") Num_Type(#1 * #2)
Message("a / b = ") Num_Type(#1 / #2)
Message("a % b = ") Num_Type(#1 % #2)</
=={{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}}==
<
let b = float2nr(input("Number 2: ") + 0)
echo "\nSum: " . (a + b)
Line 4,772 ⟶ 5,863:
" The sign of the result of the remainder operation matches the sign of
" the first operand
echo "Remainder: " . (a % b)</
=={{header|Visual Basic .NET}}==
<
Module Module1
Sub Main
Line 4,788 ⟶ 5,879:
WriteLine("Exponent " & a ^ b)
End Sub
End Module</
=={{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}}==
<
b <- (read)
prn "sum: " a+b
Line 4,799 ⟶ 5,933:
prn "integer quotient: " (int a/b)
prn "remainder: " a%b
prn "exponent: " a^b</
=={{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)")
Line 4,811 ⟶ 5,951:
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.
<
mov bx, b
xor dx, dx
Line 4,836 ⟶ 5,989:
mov remainder, dx
ret</
=={{header|XLISP}}==
<
(DISPLAY "Enter two integers separated by a space.")
(NEWLINE)
Line 4,855 ⟶ 6,008:
(DISPLAY `(REMAINDER ,(REM A B))) ; takes sign of first operand
(NEWLINE)
(DISPLAY `(EXPONENTIATION ,(EXPT A B))))</
=={{header|XPL0}}==
<
int A, B;
[A:= IntIn(0);
Line 4,867 ⟶ 6,020:
IntOut(0, A/B); CrLf(0); \truncates toward zero
IntOut(0, rem(0)); CrLf(0); \remainder's sign matches first operand (A)
]</
=={{header|XSLT}}==
<
<xsl:param name="a">5</xsl:param>
<xsl:param name="b">2</xsl:param>
Line 4,878 ⟶ 6,031:
<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></
=={{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}}==
<
read, x, y;
write, "x + y =", x + y;
Line 4,888 ⟶ 6,055:
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</
=={{header|zkl}}==
<
println("x+y = ",x + y);
println("x-y = ",x - y);
Line 4,897 ⟶ 6,064:
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</
=={{header|zonnon}}==
<
module Main;
var
Line 4,912 ⟶ 6,080:
writeln("remainder: ", i mod j);
end Main.
</syntaxhighlight>
{{Out}}
<pre>
Line 4,923 ⟶ 6,091:
remainder: 2
</pre>
=={{header|ZX Spectrum Basic}}==
<
10 PRINT a;" + ";b;" = ";a+b
20 PRINT a;" - ";b;" = ";a-b
Line 4,931 ⟶ 6,100:
50 PRINT a;" mod ";b;" = ";a-INT (a/b)*b
60 PRINT a;" to the power of ";b;" = ";a^b
</syntaxhighlight>
|