Arithmetic/Integer: Difference between revisions

m
syntax highlighting fixup automation
(Corrected tags)
m (syntax highlighting fixup automation)
Line 24:
 
=={{header|0815}}==
<langsyntaxhighlight lang=0815>
|~>|~#:end:>
<:61:x<:3d:=<:20:$==$~$=${~>%<:2c:~$<:20:~$
Line 38:
}:ml:x->{x{=>~*>{x<:1:-#:ter:^:ml:
}:ter:<:61:x<:5e:=<:20:$==$~$$=$<:62:x<:3D:=<:20:$==$~$=${{~%
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 52:
 
=={{header|11l}}==
<langsyntaxhighlight lang=11l>V a = Int(input())
V b = Int(input())
 
Line 60:
print(‘a / b = ’(a I/ b))
print(‘a % b = ’(a % b))
print(‘a ^ b = ’(a ^ b))</langsyntaxhighlight>
 
=={{header|360 Assembly}}==
Line 78:
The sign of the quotient is determined by the rules of algebra.
The remainder has the same sign as the dividend.
<langsyntaxhighlight lang=360asm>* Arithmetic/Integer 04/09/2015
ARITHINT CSECT
USING ARITHINT,R12
Line 116:
BUF DC CL12' '
YREGS
END ARITHINT</langsyntaxhighlight>
Inputs are in the code: a=53, b=11
{{out}}
Line 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.
<langsyntaxhighlight lang=6502asm>Arithmetic: PHA ;push accumulator and X register onto stack
TXA
PHA
Line 176:
TAX
PLA
RTS ;return from subroutine</langsyntaxhighlight>
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}}==
<langsyntaxhighlight lang=68000devpac>ADD.L D0,D1 ; add two numbers
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
SUB.L D1,D0 ; subtract D1 from D0
Line 190:
DIVU D1,D0
SWAP D0 ;swap the order of the 16-bit halves of D0.
RTS</langsyntaxhighlight>
 
Exponentiation doesn't exist but can be implemented in a similar fashion to multiplication on the 6502:
 
<langsyntaxhighlight lang=68000devpac>Exponent:
;raises D0 to the D1 power. No overflow protection.
MOVE.L D0,D2
Line 202:
DBRA D1,loop_exponent
;output is in D2
RTS</langsyntaxhighlight>
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<langsyntaxhighlight lang=AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program arith64.s */
Line 332:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
{{Output : }}
<PRE>
Line 344:
 
=={{header|ABAP}}==
<langsyntaxhighlight lang=ABAP>report zz_arithmetic no standard page heading.
 
" Read in the two numbers from the user.
Line 368:
write: / 'Integer quotient:', lv_result. " Truncated towards zero.
lv_result = p_first mod p_second.
write: / 'Remainder:', lv_result.</langsyntaxhighlight>
 
=={{header|ACL2}}==
<langsyntaxhighlight lang=Lisp>
:set-state-ok t
 
Line 391:
(cw "Product: ~x0~%" (* a b))
(cw "Quotient: ~x0~%" (floor a b))
(cw "Remainder: ~x0~%" (mod a b))))))</langsyntaxhighlight>
 
=={{header|Action!}}==
<langsyntaxhighlight lang=Action!>DEFINE NO_KEY="255"
DEFINE KEY_Y="43"
DEFINE KEY_N="35"
Line 429:
FI
OD
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Arithmetic_Integer.png Screenshot from Atari 8-bit computer]
Line 446:
 
=={{header|Ada}}==
<langsyntaxhighlight lang=ada>with Ada.Text_Io;
with Ada.Integer_Text_IO;
 
Line 465:
Put_Line("a**b = " & Integer'Image(A ** B));
 
end Integer_Arithmetic;</langsyntaxhighlight>
 
=={{header|Aikido}}==
<langsyntaxhighlight lang=aikido>var a = 0
var b = 0
stdin -> a // read int from stdin
Line 477:
println ("a*b=" + (a * b))
println ("a/b=" + (a / b))
println ("a%b=" + (a % b))</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 484:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{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}}
<langsyntaxhighlight lang=algol68>main:(
LONG INT a=355, b=113;
printf(($"a PLUS b = a+b = "gl$, a + b));
Line 493:
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))
)</langsyntaxhighlight>
{{out}}
<pre>
Line 515:
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.
<langsyntaxhighlight lang=algolw>begin
integer a, b;
write( "Enter 2 integers> " );
Line 528:
% operand can be integer, real or complex ) %
write( "a ^ b: ", round( a ** b ) )
end.</langsyntaxhighlight>
 
=={{header|AmigaE}}==
<langsyntaxhighlight lang=amigae>PROC main()
DEF a, b, t
WriteF('A = ')
Line 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</langsyntaxhighlight>
 
=={{header|APL}}==
<langsyntaxhighlight lang=apl>∇res ← integer_arithmetic; l; r
l ← ⎕
r ← ⎕
res ← 6 2 ⍴ 'sum' (l+r) 'diff' (l-r) 'prod' (l×r) 'quot' (⌊l÷r) 'rem' (r|l) 'pow' (l*r)
∇</langsyntaxhighlight>
 
Quotient will round down in this version.
Line 557:
=={{header|AppleScript}}==
 
<langsyntaxhighlight 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
 
Line 567:
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}</langsyntaxhighlight>
 
{{output}}
 
<langsyntaxhighlight lang=applescript>{|integers|:{-57, 2}, difference:-59, product:-114, quotient:-28, remainder:-1, exponientiation:3249.0}</langsyntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<langsyntaxhighlight lang=ARM Assembly>
 
/* ARM assembly Raspberry PI */
Line 866:
 
 
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang=rebol>a: to :integer input "give me the first number : "
b: to :integer input "give me the second number : "
 
Line 878:
print [a "/" b "=" a/b]
print [a "%" b "=" a%b]
print [a "^" b "=" a^b]</langsyntaxhighlight>
 
{{out}}
Line 893:
 
=={{header|Asymptote}}==
<langsyntaxhighlight lang=Asymptote>int a = -12;
int b = 7;
 
Line 909:
write(" división de a / b = ", division);
write(" resto de a mod b = ", resto);
write("exponenciación a ^ b = ", expo);</langsyntaxhighlight>
 
=={{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).
<langsyntaxhighlight lang=autohotkey>Gui, Add, Edit, va, 5
Gui, Add, Edit, vb, -3
Gui, Add, Button, Default, Compute
Line 931:
; fallthrough
GuiClose:
ExitApp</langsyntaxhighlight>
 
=={{header|Avail}}==
<langsyntaxhighlight lang=Avail>Method "arithmetic demo_,_" is
[
a : integer,
Line 946:
Print: “a ^ b”;
];
</syntaxhighlight>
</lang>
 
=={{header|AWK}}==
<langsyntaxhighlight lang=awk>/^[ \t]*-?[0-9]+[ \t]+-?[0-9]+[ \t]*$/ {
print "add:", $1 + $2
print "sub:", $1 - $2
Line 956:
print "mod:", $1 % $2 # same sign as first operand
print "exp:", $1 ^ $2
exit }</langsyntaxhighlight>
 
For division and modulus, Awk should act like C.
Line 966:
Same code as [[#Commodore_BASIC|Commodore BASIC]]
==={{header|BaCon}}===
<langsyntaxhighlight lang=freebasic>' Arthimetic/Integer
DECLARE a%, b%
INPUT "Enter integer A: ", a%
Line 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%))</langsyntaxhighlight>
 
==={{header|Commodore BASIC}}===
<langsyntaxhighlight lang=basic>10 INPUT "ENTER A NUMBER"; A%
20 INPUT "ENTER ANOTHER NUMBER"; B%
30 PRINT "ADDITION:";A%;"+";B%;"=";A%+B%
Line 987:
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%</langsyntaxhighlight>
 
==={{header|True BASIC}}===
<langsyntaxhighlight lang=basic>
! RosettaCode: Integer Arithmetic
! True BASIC v6.007
Line 1,006:
GET KEY done
END
</syntaxhighlight>
</lang>
==={{header|QBasic}}===
{{works with|QuickBasic|4.5}}
<langsyntaxhighlight lang=qbasic>function math(a!, b!)
print a + b
print a - b
Line 1,015:
print a / b
print a mod b
end function</langsyntaxhighlight>
Truncate towards: 0
 
Line 1,021:
 
=={{header|BASIC256}}==
<langsyntaxhighlight lang=BASIC256>
input "enter a number ?", a
input "enter another number ?", b
Line 1,031:
print "remainder or modulo " + a + " % " + b + " = " + (a % b)
print "power " + a + " ^ " + b + " = " + (a ^ b)
</syntaxhighlight>
</lang>
 
=={{header|Batch File}}==
{{works with|Windows 7| or later, haven't checked earlier versions}}
<langsyntaxhighlight lang=dos>
set /p equation=
set /a result=%equation%
echo %result%
pause
</syntaxhighlight>
</lang>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang=bbcbasic> INPUT "Enter the first integer: " first%
INPUT "Enter the second integer: " second%
Line 1,051:
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%</langsyntaxhighlight>
 
=={{header|bc}}==
<langsyntaxhighlight lang=bc>define f(a, b) {
"add: "; a + b
"sub: "; a - b
Line 1,061:
"mod: "; a % b /* same sign as first operand */
"pow: "; a ^ b
}</langsyntaxhighlight>
 
=={{header|Befunge}}==
<langsyntaxhighlight lang=befunge>&&00p"=A",,:."=B ",,,00g.55+,v
v,+55.+g00:,,,,"A+B="<
>"=B-A",,,,:00g-.55+,v
v,+55.*g00:,,,,"A*B="<
>"=B/A",,,,:00g/.55+,v
@,+55.%g00,,,,"A%B="<</langsyntaxhighlight>
 
=={{header|BQN}}==
Line 1,097:
=={{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>.
<langsyntaxhighlight lang=Bracmat> ( enter
= put$"Enter two integer numbers, separated by space:"
& get':(~/#?k_~/#?m|quit:?k)
Line 1,114:
& out$("Exponentiation:" !k^!m)
& done;
</syntaxhighlight>
</lang>
 
=={{header|Brat}}==
Inspired by the second VBScript version.
<langsyntaxhighlight lang=brat>x = ask("First number: ").to_i
y = ask("Second number: ").to_i
 
Line 1,124:
#Remainder uses sign of right hand side
[:+ :- :* :/ :% :^].each { op |
p "#{x} #{op} #{y} = #{x.call_method op, y}"</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang=c>#include <stdio.h>
#include <stdlib.h>
 
Line 1,143:
printf("a%%b = %d\n", a%b); /* same sign as first operand (in C99) */
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang=csharp>using System;
 
class Program
Line 1,162:
Console.WriteLine("{0} to the power of {1} = {2}", a, b, Math.Pow(a, b));
}
}</langsyntaxhighlight>
{{out}}
<pre>5 + 3 = 8
Line 1,172:
 
=={{header|C++}}==
<langsyntaxhighlight lang=cpp>#include <iostream>
 
int main()
Line 1,183:
std::cout << "a/b = " << a/b << ", remainder " << a%b << "\n";
return 0;
}</langsyntaxhighlight>
 
=={{header|Chef}}==
 
<langsyntaxhighlight lang=Chef>Number Soup.
 
Only reads single values.
Line 1,222:
Clean 1st mixing bowl.
 
Serves 5.</langsyntaxhighlight>
 
=={{header|Clipper}}==
<langsyntaxhighlight lang=visualfoxpro>procedure Test( a, b )
? "a+b", a + b
? "a-b", a - b
Line 1,235:
// Exponentiation is also a base arithmetic operation
? "a**b", a ** b
return</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang=clojure>(defn myfunc []
(println "Enter x and y")
(let [x (read), y (read)]
(doseq [op '(+ - * / Math/pow rem)]
(let [exp (list op x y)]
(printf "%s=%s\n" exp (eval exp))))))</langsyntaxhighlight>
 
<pre>user=> (myfunc)
Line 1,258:
 
=={{header|COBOL}}==
<langsyntaxhighlight lang=cobol> IDENTIFICATION DIVISION.
PROGRAM-ID. Int-Arithmetic.
 
Line 1,301:
 
GOBACK
.</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang=lisp>(defun arithmetic (&optional (a (read *query-io*)) (b (read *query-io*)))
(mapc
(lambda (op)
(format t "~a => ~a~%" (list op a b) (funcall (symbol-function op) a b)))
'(+ - * mod rem floor ceiling truncate round expt))
(values))</langsyntaxhighlight>
 
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,336:
=={{header|Component Pascal}}==
Works with Gardens Point Component Pascal
<langsyntaxhighlight lang=oberon2>
MODULE Arithmetic;
IMPORT CPmain,Console,RTS;
Line 1,365:
Console.WriteString("x MOD y >");Console.WriteInt(x MOD y,6);Console.WriteLn;
END Arithmetic.
</syntaxhighlight>
</lang>
command: <i>cprun Arithmetic 12 23</i><br/>
{{out}}
Line 1,376:
</pre>
Works with BlackBox Component Builder
<langsyntaxhighlight lang=oberon2>
MODULE Arithmetic;
IMPORT StdLog,DevCommanders,TextMappers;
Line 1,410:
END Go;
END Arithmetic.
</syntaxhighlight>
</lang>
Command: Arithmetic.Go 12 23 ~ <br/>
{{out}}
Line 1,422:
 
=={{header|Crystal}}==
<langsyntaxhighlight lang=crystal>a = gets.not_nil!.to_i64
b = gets.not_nil!.to_i64
 
Line 1,432:
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>
</lang>
 
=={{header|D}}==
<langsyntaxhighlight lang=d>import std.stdio, std.string, std.conv;
 
void main() {
Line 1,451:
writeln("a % b = ", a % b);
writeln("a ^^ b = ", a ^^ b);
}</langsyntaxhighlight>
{{out}}
<pre>a = -16, b = 5
Line 1,463:
===Shorter Version===
Same output.
<langsyntaxhighlight lang=d>import std.stdio, std.string, std.conv, std.meta;
 
void main() {
Line 1,475:
foreach (op; AliasSeq!("+", "-", "*", "/", "%", "^^"))
mixin(`writeln("a ` ~ op ~ ` b = ", a` ~ op ~ `b);`);
}</langsyntaxhighlight>
Division and modulus are defined as in C99.
 
=={{header|dc}}==
<langsyntaxhighlight lang=dc>[Enter 2 integers on 1 line.
Use whitespace to separate. Example: 2 3
Use underscore for negative integers. Example: _10
Line 1,488:
[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</langsyntaxhighlight>
 
=={{header|DCL}}==
<langsyntaxhighlight lang=DCL>$ inquire a "Enter first number"
$ a = f$integer( a )
$ inquire b "Enter second number"
Line 1,498:
$ write sys$output "a - b = ", a - b
$ write sys$output "a * b = ", a * b
$ write sys$output "a / b = ", a / b ! truncates down</langsyntaxhighlight>
{{out}}
<pre>$ @arithmetic_integer
Line 1,516:
 
=={{header|Delphi}}==
<langsyntaxhighlight lang=Delphi>program IntegerArithmetic;
 
{$APPTYPE CONSOLE}
Line 1,534:
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.</langsyntaxhighlight>
 
=={{header|DWScript}}==
<langsyntaxhighlight lang=delphi>var a := StrToInt(ParamStr(0));
var b := StrToInt(ParamStr(1));
 
Line 1,545:
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))]));</langsyntaxhighlight>
 
=={{header|Dyalect}}==
Line 1,553:
Dyalect has no operator for exponential.
 
<langsyntaxhighlight lang=Dyalect>let a = 6
let b = 4
Line 1,560:
print("product = \(a*b)")
print("Integer quotient = \(a/b)")
print("Remainder = \(a%b)")</langsyntaxhighlight>
 
=={{header|E}}==
 
<langsyntaxhighlight lang=e>def arithmetic(a :int, b :int) {
return `$\
Sum: ${a + b}
Line 1,571:
Quotient: ${a // b}
Remainder: ${a % b}$\n`
}</langsyntaxhighlight>
 
=={{header|EasyLang}}==
Line 1,582:
print a div b
print a mod b
print pow a b</langsyntaxhighlight>
 
=={{header|ECL}}==
<langsyntaxhighlight lang=ECL>
ArithmeticDemo(INTEGER A,INTEGER B) := FUNCTION
ADDit := A + B;
Line 1,617:
This default behavior can be changed
*/
</syntaxhighlight>
</lang>
 
=={{header|Efene}}==
 
<langsyntaxhighlight lang=efene>@public
run = fn () {
 
Line 1,635:
io.format("Quotient: ~p~n", [A / B])
io.format("Remainder: ~p~n", [A % B])
}</langsyntaxhighlight>
 
=={{header|Eiffel}}==
{{works with|SmartEiffel|2.4}}
In a file called main.e:
<langsyntaxhighlight lang=eiffel>class MAIN
creation make
feature make is
Line 1,668:
print("%N");
end
end</langsyntaxhighlight>
Note that there actually is a builtin modulo operator (\\). However, it seems impossible to use that instruction with SmartEiffel.
 
=={{header|Elena}}==
ELENA 4.x :
<langsyntaxhighlight lang=elena>import system'math;
import extensions;
 
Line 1,687:
console.printLine(a," % ",b," = ",a.mod:b); // matches sign of first operand
console.printLine(a," ^ ",b," = ",a ^ b);
}</langsyntaxhighlight>
 
=={{header|Elixir}}==
{{works with|Elixir|1.4}}
<langsyntaxhighlight lang=Elixir>defmodule Arithmetic_Integer do
# Function to remove line breaks and convert string to int
defp get_int(msg) do
Line 1,715:
end
 
Arithmetic_Integer.task</langsyntaxhighlight>
 
{{out}}
Line 1,781:
 
=={{header|Emojicode}}==
<langsyntaxhighlight lang=Emojicode>🏁🍇
🍺🔢🆕🔡▶️👂🏼❗ 10❗️ ➡️ x 💭 Get first number
🍺🔢🆕🔡▶️👂🏼❗ 10❗️ ➡️ y 💭 Get second number
Line 1,789:
😀 🔤Quotient: 🧲x➗️y🧲🔤 ❗ 💭 Rounds towards 0
😀 🔤Remainder: 🧲x🚮️y🧲🔤 ❗ 💭 Matches sign of first operand
🍉️</langsyntaxhighlight>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang=erlang>% Implemented by Arjun Sunel
-module(arith).
-export([start/0]).
Line 1,806:
halt()
end.
</syntaxhighlight>
</lang>
 
=={{header|ERRE}}==
Line 1,829:
PRINT("Power ";A;"^";B;"=";(A^B))
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>Enter a number ? 12
Line 1,847:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang=euphoria>include get.e
 
integer a,b
Line 1,859:
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))</langsyntaxhighlight>
 
{{out}}
Line 1,876:
 
For sum, type in C1
<langsyntaxhighlight lang=excel>
=$A1+$B1
</syntaxhighlight>
</lang>
 
For difference, type in D1
<langsyntaxhighlight lang=excel>
=$A1-$B1
</syntaxhighlight>
</lang>
 
For product, type in E1
<langsyntaxhighlight lang=excel>
=$A1*$B1
</syntaxhighlight>
</lang>
 
For quotient, type in F1
<langsyntaxhighlight lang=excel>
=QUOTIENT($A1,$B1)
</syntaxhighlight>
</lang>
 
For remainder, type in G1
<langsyntaxhighlight lang=excel>
=MOD($A1,$B1)
</syntaxhighlight>
</lang>
 
For exponentiation, type in H1
<langsyntaxhighlight lang=excel>
=$A1^$B1
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
As F# is a functional language, we can easily create a list of pairs of the string name of a function and the function itself to iterate over printing the operation and applying the function to obtain the result:
<langsyntaxhighlight 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>
</lang>
For example, the output with the arguments 4 and 3 is:
<langsyntaxhighlight lang=fsharp>
4 + 3 = 7
4 - 3 = 1
Line 1,920:
4 / 3 = 1
4 % 3 = 1
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
<langsyntaxhighlight lang=factor>USING: combinators io kernel math math.functions math.order
math.parser prettyprint ;
 
Line 1,939:
[ gcd "gcd: " write . drop ]
[ lcm "lcm: " write . ]
} 2cleave</langsyntaxhighlight>
 
{{out}}
Line 1,960:
 
=={{header|FALSE}}==
<langsyntaxhighlight lang=false>12 7
\$@$@$@$@$@$@$@$@$@$@\ { 6 copies }
"sum = "+."
Line 1,967:
quotient = "/."
modulus = "/*-."
"</langsyntaxhighlight>
 
=={{header|Fermat}}==
Integer division rounds towards zero; remainders are always positive regardless of the signs of the numbers.
<langsyntaxhighlight lang=fermat>
?a;
?b;
Line 1,980:
!!('Remainder: a|b=',a|b);
!!('Exponentiation: a^b=',a^b);
</syntaxhighlight>
</lang>
{{out}}<pre>
>a := 64
Line 1,994:
=={{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 ).
<langsyntaxhighlight lang=forth>: arithmetic ( a b -- )
cr ." a=" over . ." b=" dup .
cr ." a+b=" 2dup + .
Line 2,000:
cr ." a*b=" 2dup * .
cr ." a/b=" /mod .
cr ." a mod b = " . cr ;</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang=forth>FM/MOD ( d n -- mod div ) \ floored
SM/REM ( d n -- rem div ) \ symmetric
M* ( n n -- d )</langsyntaxhighlight>
 
In addition, there are unsigned variants.
 
<langsyntaxhighlight lang=forth>UM/MOD ( ud u -- umod udiv )
UM* ( u u -- ud )</langsyntaxhighlight>
 
=={{header|Fortran}}==
In ANSI FORTRAN 77 or later:
<langsyntaxhighlight lang=fortran> INTEGER A, B
PRINT *, 'Type in two integer numbers separated by white space',
+ ' and press ENTER'
Line 2,028:
+ 'exponentiation is an intrinsic op in Fortran, so...'
PRINT *, ' A ** B = ', (A ** B)
END</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang=freebasic>' FB 1.05.0 Win64
 
Dim As Integer i, j
Line 2,046:
 
' Remainder (for which FB uses the Mod operator) will, if non-zero, match the sign
' of the first operand</langsyntaxhighlight>
 
Sample input and output:-
Line 2,061:
 
=={{header|friendly interactive shell}}==
<langsyntaxhighlight lang=fishshell>
read a
read b
Line 2,070:
echo 'a % b =' (math "$a % $b") # Remainder
echo 'a ^ b =' (math "$a ^ $b") # Exponentation
</syntaxhighlight>
</lang>
 
=={{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.
<langsyntaxhighlight lang=frink>
[a,b] = input["Enter numbers",["a","b"]]
ops=["+", "-", "*", "/", "div" ,"mod" ,"^"]
Line 2,082:
println["$str = " + eval[str]]
}
</syntaxhighlight>
</lang>
 
{{out}}
<langsyntaxhighlight lang=frink>
10 + 20 = 30
10 - 20 = -10
Line 2,093:
10 mod 20 = 10
10 ^ 20 = 100000000000000000000
</syntaxhighlight>
</lang>
 
=={{header|FutureBasic}}==
Basic program
<langsyntaxhighlight lang=futurebasic>
window 1, @"Integer Arithmetic", ( 0, 0, 400, 300 )
 
Line 2,112:
 
HandleEvents
</syntaxhighlight>
</lang>
 
Output:
Line 2,126:
 
Standalone Intel, M1, M2 Macintosh application with user input
<langsyntaxhighlight lang=futurebasic>
 
_window = 1
Line 2,239:
 
HandleEvents
</syntaxhighlight>
</lang>
 
Output:
Line 2,256:
 
=={{header|Gambas}}==
<langsyntaxhighlight lang=gambas>Public Sub Main()
Dim a, b As String
Dim c, d As Integer
Line 2,274:
 
End
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,288:
 
=={{header|GAP}}==
<langsyntaxhighlight lang=gap>run := function()
local a, b, f;
f := InputTextUser();
Line 2,302:
Display(Concatenation(String(a), " ^ ", String(b), " = ", String(a ^ b)));
CloseStream(f);
end;</langsyntaxhighlight>
 
=={{header|Genie}}==
Note: Using ''init:int'' and the ''return'' from the init block was introduced in release 0.43.92, February 2019.
 
<langsyntaxhighlight lang=genie>[indent=4]
/*
Arithmethic/Integer, in Genie
Line 2,327:
print "\nGenie does not include a raise to power operator"
 
return 0</langsyntaxhighlight>
 
{{out}}
Line 2,341:
 
=={{header|GEORGE}}==
<langsyntaxhighlight lang=GEORGE>R (m) ;
R (n) ;
m n + P;
Line 2,347:
m n × P;
m n div P;
m n rem P;</langsyntaxhighlight>
 
=={{header|Go}}==
===int===
<langsyntaxhighlight lang=go>package main
 
import "fmt"
Line 2,365:
fmt.Printf("%d %% %d = %d\n", a, b, a%b) // same sign as first operand
// no exponentiation operator
}</langsyntaxhighlight>
{{out|Example run}}
<pre>
Line 2,376:
</pre>
===big.Int===
<langsyntaxhighlight lang=go>package main
 
import (
Line 2,404:
 
// as with int, no exponentiation operator
}</langsyntaxhighlight>
{{out|Example run}}
<pre>
Line 2,419:
=={{header|Groovy}}==
'''Solution:'''
<langsyntaxhighlight lang=groovy>def arithmetic = { a, b ->
println """
a + b = ${a} + ${b} = ${a + b}
Line 2,432:
a ** b = ${a} ** ${b} = ${a ** b}
"""
}</langsyntaxhighlight>
 
'''Test:'''
<syntaxhighlight lang =groovy>arithmetic(5,3)</langsyntaxhighlight>
 
{{out}}
Line 2,450:
 
=={{header|Harbour}}==
<langsyntaxhighlight lang=visualfoxpro>procedure Test( a, b )
? "a+b", a + b
? "a-b", a - b
Line 2,460:
// Exponentiation is also a base arithmetic operation
? "a**b", a ** b
return</langsyntaxhighlight>
 
=={{header|Haskell}}==
 
<langsyntaxhighlight lang=haskell>main = do
a <- readLn :: IO Integer
b <- readLn :: IO Integer
Line 2,478:
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)</langsyntaxhighlight>
 
=={{header|Haxe}}==
<langsyntaxhighlight lang=haxe>class BasicIntegerArithmetic {
public static function main() {
var args =Sys.args();
Line 2,493:
trace("a%b = " + (a%b));
}
}</langsyntaxhighlight>
 
=={{header|HicEst}}==
All numeric is 8-byte-float. Conversions are by INT, NINT, FLOOR, CEILING, or Formatted IO
<langsyntaxhighlight lang=hicest>DLG(Edit=A, Edit=B, TItle='Enter numeric A and B')
WRITE(Name) A, B
WRITE() ' A + B = ', A + B
Line 2,509:
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</langsyntaxhighlight>
<langsyntaxhighlight lang=hicest>A=5; B=-4;
A + B = 1
A - B = 9
Line 2,521:
remainder of A / B = 1
A to the power of B = 16E-4
A to the power of B = 16E-4 </langsyntaxhighlight>
 
=={{header|HolyC}}==
<langsyntaxhighlight lang=holyc>I64 *a, *b;
a = Str2I64(GetStr("Enter your first number: "));
b = Str2I64(GetStr("Enter your second number: "));
Line 2,537:
Print("a % b = %d\n", a % b); /* same sign as first operand */
Print("a ` b = %d\n", a ` b);
}</langsyntaxhighlight>
 
=={{header|i}}==
<langsyntaxhighlight lang=i>main
a $= integer(in(' ')); ignore
b $= integer(in('\n')); ignore
Line 2,550:
print("Modulus:" , a % b) // same sign as first operand
print("Exponent:" , a ^ b)
}</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight lang=Icon>procedure main()
writes("Input 1st integer a := ")
a := integer(read())
Line 2,565:
write(" a % b = ",a%b, " remainder sign matches a")
write(" a ^ b = ",a^b)
end</langsyntaxhighlight>
 
=={{header|Inform 7}}==
 
<langsyntaxhighlight lang=inform7>Enter Two Numbers is a room.
 
Numerically entering is an action applying to one number. Understand "[number]" as numerically entering.
Line 2,592:
Equation - Division Formula
Q = A / B
where Q is a number, A is a number, and B is a number.</langsyntaxhighlight>
 
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}}==
<langsyntaxhighlight lang=j>calc =: + , - , * , <.@% , |~ , ^</langsyntaxhighlight>
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.
<langsyntaxhighlight lang=j> 17 calc 3
20 14 51 5 2 4913</langsyntaxhighlight>
 
The function <code>bia</code> assembles these results, textually:
 
<langsyntaxhighlight lang=j>labels =: ];.2 'Sum: Difference: Product: Quotient: Remainder: Exponentiation: '
combine =: ,. ":@,.
bia =: labels combine calc
Line 2,614:
Quotient: 5
Remainder: 2
Exponentiation: 4913</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang=java>import java.util.Scanner;
 
public class IntegerArithmetic {
Line 2,638:
System.out.println("remainder of a / b = " + remainder); // same sign as first operand
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 2,645:
{{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.
<langsyntaxhighlight lang=javascript>var a = parseInt(get_input("Enter an integer"), 10);
var b = parseInt(get_input("Enter an integer"), 10);
 
Line 2,670:
print(prompt);
}
}</langsyntaxhighlight>
{{out}}
<pre>Enter an integer
Line 2,684:
remainder: a % b = -21</pre>
===Node.JS===
<langsyntaxhighlight lang=javascript>// Invoked as node script_name.js <a> <b>. Positions 0 and 1 in the argv array contain 'node' and 'script_name.js' respectively
var a = parseInt(process.argv[2], 10);
var b = parseInt(process.argv[3], 10);
Line 2,698:
console.log('a * b = %d', product);
console.log('a / b = %d', division);
console.log('a % b = %d', remainder);</langsyntaxhighlight>
{{out}}
<pre>$ node arith.js 10 7
Line 2,708:
 
=={{header|jq}}==
<langsyntaxhighlight lang=jq># Lines which do not have two integers are skipped:
 
def arithmetic:
Line 2,725:
 
arithmetic
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,757:
 
=={{header|Jsish}}==
<langsyntaxhighlight lang=javascript>"use strict";
/* Arthimetic/Integer, in Jsish */
var line = console.input();
Line 2,789:
Exponentiation A to the power B is 2401
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 2,796:
 
=={{header|Julia}}==
<langsyntaxhighlight lang=Julia>function arithmetic (a = parse(Int, readline()), b = parse(Int, readline()))
for op in [+,-,*,div,rem]
println("a $op b = $(op(a,b))")
end
end</langsyntaxhighlight>
{{Out}}
<pre>julia> arithmetic()
Line 2,812:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang=scala>// version 1.1
 
fun main(args: Array<String>) {
Line 2,852:
println()
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,881:
=={{header|Lambdatalk}}==
Translation of Racket
<langsyntaxhighlight lang=Scheme>
{def arithmetic
{lambda {:x :y}
Line 2,902:
applying > on 8 & 12 returns false
applying < on 8 & 12 returns true
</syntaxhighlight>
</lang>
 
=={{header|Lasso}}==
<langsyntaxhighlight lang=Lasso>local(a = 6, b = 4)
#a + #b // 10
#a - #b // 2
Line 2,912:
#a % #b // 2
math_pow(#a,#b) // 1296
math_pow(#b,#a) // 4096</langsyntaxhighlight>
 
=={{header|LFE}}==
 
<langsyntaxhighlight lang=lisp>
(defmodule arith
(export all))
Line 2,931:
; 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>
</lang>
 
Usage from the LFE REPL:
<langsyntaxhighlight lang=lisp>
> (slurp '"arith.lfe")
#(ok arith)
Line 2,946:
2 rem 8 = 2
ok
</syntaxhighlight>
</lang>
 
=={{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>
<lang lb>
input "Enter the first integer: "; first
input "Enter the second integer: "; second
Line 2,960:
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>
</lang>
 
=={{header|LIL}}==
<langsyntaxhighlight lang=tcl># Arithmetic/Integer, in LIL
write "Enter two numbers separated by space: "
if {[canread]} {set line [readline]}
Line 2,976:
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"</langsyntaxhighlight>
 
{{out}}
Line 3,000:
 
=={{header|Lingo}}==
<langsyntaxhighlight lang=Lingo>-- X, Y: 2 editable field members, shown as sprites in the current GUI
x = integer(member("X").text)
y = integer(member("Y").text)
Line 3,009:
put "Quotient: " , x / y -- Truncated towards zero
put "Remainder: " , x mod y -- Result has sign of left operand
put "Exponent: " , power(x, y)</langsyntaxhighlight>
 
=={{header|Little}}==
<langsyntaxhighlight lang=C># Maybe you need to import the mathematical funcions
# from Tcl with:
# eval("namespace path ::tcl::mathfunc");
Line 3,026:
puts("${a} / ${b} = ${a/b}, remainder ${a%b}");
puts("${a} to the power of ${b} = ${(int)pow(a,b)}");
}</langsyntaxhighlight>
 
=={{header|LiveCode}}==
<langsyntaxhighlight lang=LiveCode>ask "enter 2 numbers (comma separated)"
if it is not empty then
put item 1 of it into n1
Line 3,040:
combine ai using comma and colon
put ai
end if</langsyntaxhighlight>
Examples<lang>-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</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang=logo>to operate :a :b
(print [a =] :a)
(print [b =] :b)
Line 3,056:
(print [a / b =] int :a / :b)
(print [a mod b =] modulo :a :b)
end</langsyntaxhighlight>
 
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}}==
<langsyntaxhighlight lang=lse64>over : 2 pick
2dup : over over
 
Line 3,070:
" A*B=" ,t 2dup * , nl \
" A/B=" ,t 2dup / , nl \
" A%B=" ,t % , nl</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang=lua>local x = io.read()
local y = io.read()
 
Line 3,081:
print ("Quotient: " , (x / y)) -- Does not truncate
print ("Remainder: " , (x % y)) -- Result has sign of right operand
print ("Exponent: " , (x ^ y))</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Line 3,089:
 
 
<langsyntaxhighlight lang=M2000 Interpreter>
MODULE LikeCommodoreBasic {
\\ ADDITION: EUCLIDEAN DIV# & MOD# AND ** FOR POWER INCLUDING ^
Line 3,137:
}
IntegerTypes
</syntaxhighlight>
</lang>
 
=={{header|M4}}==
 
Because of the particular nature of M4, the only user-input is the code itself. Anyway the following code can be used:
<langsyntaxhighlight lang=m4>eval(A+B)
eval(A-B)
eval(A*B)
eval(A/B)
eval(A%B)</langsyntaxhighlight>
 
once saved in a file, e.g. <tt>operations.m4</tt>:
Line 3,154:
or using a sort of ''driver'':
 
<langsyntaxhighlight lang=m4>define(`A', 4)dnl
define(`B', 6)dnl
include(`operations.m4')</langsyntaxhighlight>
 
=={{header|Maple}}==
These operations are all built-in. As all operations are exact, there are no rounding issues involved.
<langsyntaxhighlight lang=Maple>
DoIt := proc()
local a := readstat( "Input an integer: " ):
Line 3,171:
NULL # quiet return
end proc:
</syntaxhighlight>
</lang>
Here is an example of calling DoIt.
<langsyntaxhighlight lang=Maple>
> DoIt();
Input an integer: 15;
Line 3,183:
Remainder = 3
>
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Mathematica has all the function built-in to handle this task. Example:
<langsyntaxhighlight lang=Mathematica>a = Input["Give me an integer please!"];
b = Input["Give me another integer please!"];
Print["You gave me ", a, " and ", b];
Line 3,195:
Print["integer quotient: ", Quotient[a, b]];
Print["remainder: ", Mod[a, b]];
Print["exponentiation: ", a^b];</langsyntaxhighlight>
gives back for input 17 and 3:
<pre>You gave me 17 and 3
Line 3,259:
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight lang=octave>disp("integer a: "); a = scanf("%d", 1);
disp("integer b: "); b = scanf("%d", 1);
a+b
Line 3,266:
floor(a/b)
mod(a,b)
a^b</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang=maxima>block(
[a: read("a"), b: read("b")],
print(a + b),
Line 3,278:
print(remainder(a, b)),
a^b
);</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<langsyntaxhighlight lang=maxscript>x = getKBValue prompt:"First number"
y = getKBValue prompt:"Second number:"
 
Line 3,288:
format "Product: %\n" (x * y)
format "Quotient: %\n" (x / y)
format "Remainder: %\n" (mod x y)</langsyntaxhighlight>
 
=={{header|Mercury}}==
Line 3,334:
io.set_exit_status(1, !IO)
).
</syntaxhighlight>
</lang>
 
=={{header|Metafont}}==
 
<langsyntaxhighlight lang=metafont>string s[];
message "input number a: ";
s1 := readstring;
Line 3,355:
outp("mod");
 
end</langsyntaxhighlight>
 
=={{header|min}}==
{{works with|min|0.19.3}}
<langsyntaxhighlight lang=min>(concat dup -> ' prepend "$1 -> $2" swap % puts!) :show
 
("Enter an integer" ask int) 2 times ' prepend
('+ '- '* 'div 'mod) quote-map ('show concat) map cleave</langsyntaxhighlight>
{{out}}
<pre>
Line 3,381:
ИП0 ИП1 / [x] С/П
ИП0 ^ ИП1 / [x] ИП1 * - С/П
ИП1 ИП0 x^y С/П</langsyntaxhighlight>
 
=={{header|ML/I}}==
Line 3,387:
and then output the results to 'standard output' or similar.
 
<langsyntaxhighlight lang=ML/I>MCSKIP "WITH" NL
"" Arithmetic/Integer
"" assumes macros on input stream 1, terminal on stream 2
Line 3,401:
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.</langsyntaxhighlight>
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang=modula2>MODULE ints;
 
IMPORT InOut;
Line 3,420:
InOut.WriteString ("a MOD b = "); InOut.WriteInt (a MOD b, 9); InOut.WriteLn;
InOut.WriteLn;
END ints.</langsyntaxhighlight>Producing:<pre>$$ ints
Enter two integer numbers : 12 7
a + b = 19
Line 3,437:
 
=={{header|Modula-3}}==
<langsyntaxhighlight lang=modula3>MODULE Arith EXPORTS Main;
 
IMPORT IO, Fmt;
Line 3,451:
IO.Put("a DIV b = " & Fmt.Int(a DIV b) & "\n");
IO.Put("a MOD b = " & Fmt.Int(a MOD b) & "\n");
END Arith.</langsyntaxhighlight>
 
=={{header|MUMPS}}==
Line 3,462:
find out the beauty of cyclic algebra as formulated by Niels Henrik Abel (August 5, 1802 – April 6, 1829).</p>
 
<langsyntaxhighlight lang=MUMPS>Arith(first,second) ; Mathematical operators
Write "Plus",?12,first,"+",second,?25," = ",first+second,!
Write "Minus",?12,first,"-",second,?25," = ",first-second,!
Line 3,505:
Modulo 0#2 = 0
And 0&2 = 0
Or 0!2 = 1</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
{{trans|Python}}
<langsyntaxhighlight lang=Nanoquery>print "Number 1: "
x = int(input())
print "Number 2: "
Line 3,520:
 
println format("Remainder: %d", x % y)
println format("Power: %d", x ^ y)</langsyntaxhighlight>
 
{{out}}
Line 3,534:
=={{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.
<langsyntaxhighlight lang=Nemerle>using System;
class Program
Line 3,550:
Console.WriteLine("{0} ** {1} = {2}", a, b, a ** b);
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
{{trans|REXX}}
<langsyntaxhighlight lang=NetRexx>/* NetRexx */
 
options replace format comments java crossref symbols binary
Line 3,567:
 
return
</syntaxhighlight>
</lang>
{{out}}
<pre style="height: 15ex; overflow:scroll;">
Line 3,581:
=={{header|NewLISP}}==
 
<langsyntaxhighlight lang=NewLISP>; integer.lsp
; oofoe 2012-01-17
 
Line 3,605:
 
(exit) ; NewLisp normally goes to listener after running script.
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,627:
 
Define new operator using an atlas of operators:
<langsyntaxhighlight lang=nial> arithmetic is OP A B{[first,last,+,-,*,quotient,mod,power] A B}</langsyntaxhighlight>
 
Test new operator:
<langsyntaxhighlight lang=nial> -23 arithmetic 7
-23 7 -16 -30 -161 -4 5 -3404825447</langsyntaxhighlight>
 
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,643:
Nial definition of <code>quotient</code>:
 
<langsyntaxhighlight lang=nial>A quotient B =f= floor (A / B)</langsyntaxhighlight>
 
<code>floor</code> rounds towards negative infinity (next lower integer).
 
=={{header|Nim}}==
<langsyntaxhighlight lang=nim>import parseopt, strutils
var
Line 3,671:
echo("a mod b: " & $(a mod b)) # sign(a mod b)==sign(a) if sign(a)!=sign(b)
echo("a ^ b : " & $(a ^ b))
</syntaxhighlight>
</lang>
Execute: Aritmint 4 5
{{out}}
Line 3,687:
=={{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.
<langsyntaxhighlight lang=nsis>Function Arithmetic
Push $0
Push $1
Line 3,710:
Pop $1
Pop $0
FunctionEnd</langsyntaxhighlight>
 
=={{header|Oberon-2}}==
Oxford Oberon-2
<langsyntaxhighlight lang=oberon2>
MODULE Arithmetic;
IMPORT In, Out;
Line 3,727:
Out.String("x MOD y >");Out.Int(x MOD y,6);Out.Ln;
END Arithmetic.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,739:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang=objeck>bundle Default {
class Arithmetic {
function : Main(args : System.String[]) ~ Nil {
Line 3,755:
}
}
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang=ocaml>let _ =
let a = read_int ()
and b = read_int () in
Line 3,766:
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 *)</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight lang=Oforth>: integers (a b -- )
"a + b =" . a b + .cr
"a - b =" . a b - .cr
Line 3,777:
"a mod b =" . a b mod .cr
"a pow b =" . a b pow .cr
;</langsyntaxhighlight>
 
{{out}}
Line 3,793:
=={{header|Ol}}==
 
<langsyntaxhighlight lang=scheme>
(define a 8)
(define b 12)
Line 3,815:
(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>
</lang>
{{out}}
<pre>
Line 3,836:
=={{header|Onyx}}==
 
<langsyntaxhighlight lang=onyx># Most of this long script is mere presentation.
# All you really need to do is push two integers onto the stack
# and then execute add, sub, mul, idiv, or pow.
Line 3,878:
} bind def
 
ClearScreen ShowPreamble $A GetInt $B GetInt ShowResults</langsyntaxhighlight>
 
{{out}}
Line 3,899:
=={{header|Openscad}}==
 
<langsyntaxhighlight lang=openscad>echo (a+b); /* Sum */
echo (a-b); /* Difference */
echo (a*b); /* Product */
echo (a/b); /* Quotient */
echo (a%b); /* Modulus */</langsyntaxhighlight>
 
=={{header|Oz}}==
<langsyntaxhighlight lang=oz>declare
StdIn = {New class $ from Open.file Open.text end init(name:stdin)}
 
Line 3,924:
"A^B = "#{Pow A B}
]
System.showInfo}</langsyntaxhighlight>
 
=={{header|Panda}}==
Use reflection to get all functions defined on numbers taking number and returning number.
<langsyntaxhighlight lang=panda>a=3 b=7 func:_bbf__number_number_number =>f.name.<b> '(' a b ')' ' => ' f(a b) nl</langsyntaxhighlight>
 
{{out}}
Line 3,946:
=={{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.
<langsyntaxhighlight lang=parigp>arith(a,b)={
print(a+b);
print(a-b);
Line 3,953:
print(a%b);
print(a^b);
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang=pascal>program arithmetic(input, output)
 
var
Line 3,969:
writeln('a^b = ',Power(a,b):4:2); {real power}
writeln('a^b = ',IntPower(a,b):4:2); {integer power}
end.</langsyntaxhighlight>
 
=={{header|Perl}}==
{{works with|Perl|5.x}}
<langsyntaxhighlight lang=perl>my $a = <>;
my $b = <>;
 
Line 3,983:
"remainder: ", $a % $b, "\n",
"exponent: ", $a ** $b, "\n"
;</langsyntaxhighlight>
 
=={{header|Phix}}==
Line 3,989:
{{libheader|Phix/online}}
You can run this online [http://phix.x10.mx/p2js/ArithInt.htm here] (layout/space is not perfected yet).
<!--<langsyntaxhighlight 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>
Line 4,034:
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</langsyntaxhighlight>-->
{{out}}
With an input of "2 3"
Line 4,049:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight lang=Phixmonti>def printOp
swap print print nl
enddef
Line 4,062:
"int(a / b) = " a b / int printOp
"a mod b = " a b mod printOp
"a ^ b = " a b power printOp</langsyntaxhighlight>
 
=={{header|PHL}}==
 
<langsyntaxhighlight lang=phl>module arith;
 
extern printf;
Line 4,084:
return 0;
]</langsyntaxhighlight>
 
=={{header|PHP}}==
<langsyntaxhighlight lang=php><?php
$a = fgets(STDIN);
$b = fgets(STDIN);
Line 4,099:
"remainder: ", $a % $b, "\n",
"power: ", $a ** $b, "\n"; // PHP 5.6+ only
?></langsyntaxhighlight>
 
=={{header|Picat}}==
<langsyntaxhighlight lang=Picat>main =>
X = read_int(),
Y = read_int(),
Line 4,109:
printf("%d %w %d = %d\n", X, Op, Y, R)
end.
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,122:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight lang=PicoLisp>(de math (A B)
(prinl "Add " (+ A B))
(prinl "Subtract " (- A B))
Line 4,129:
(prinl "Div/rnd " (*/ A B)) # Rounds to next integer
(prinl "Modulus " (% A B)) # Sign of the first operand
(prinl "Power " (** A B)) )</langsyntaxhighlight>
 
=={{header|Piet}}==
Line 4,172:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang=PL/I>
get list (a, b);
put skip list (a+b);
Line 4,179:
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. */</langsyntaxhighlight>
 
=={{header|Plain English}}==
<langsyntaxhighlight lang=plainenglish>To run:
Start up.
Demonstrate integer arithmetic.
Line 4,207:
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.</langsyntaxhighlight>
{{out}}
<pre>
Line 4,222:
=={{header|Pop11}}==
 
<langsyntaxhighlight lang=pop11>;;; Setup token reader
vars itemrep;
incharitem(charin) -> itemrep;
Line 4,232:
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');</langsyntaxhighlight>
 
=={{header|PostScript}}==
<langsyntaxhighlight lang=ps>/arithInteger {
/x exch def
/y exch def
Line 4,244:
x y mod =
x y exp =
} def</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang=powershell>$a = [int] (Read-Host First Number)
$b = [int] (Read-Host Second Number)
 
Line 4,255:
Write-Host "Quotient: $($a / $b)"
Write-Host "Quotient, round to even: $([Math]::Round($a / $b))"
Write-Host "Remainder, sign follows first: $($a % $b)"</langsyntaxhighlight>
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 4,261:
 
No exponentiation operator exists, but can be worked around with the .NET BCL:
<langsyntaxhighlight lang=powershell>[Math]::Pow($a, $b)</langsyntaxhighlight>
 
=={{header|Processing}}==
<langsyntaxhighlight lang=Processing>int a = 7, b = 5;
 
println(a + " + " + b + " = " + (a + b));
Line 4,270:
println(a + " * " + b + " = " + (a * b));
println(a + " / " + b + " = " + (a / b)); //Rounds towards zero
println(a + " % " + b + " = " + (a % b)); //Same sign as first operand</langsyntaxhighlight>
{{out}}
<pre>7 + 5 = 12
Line 4,279:
 
=={{header|ProDOS}}==
<langsyntaxhighlight lang=ProDOS>IGNORELINE Note: This example includes the math module.
include arithmeticmodule
:a
Line 4,297:
editvar /newvar /value=d /title=Do you want to calculate more numbers?
if -d- /hasvalue yes goto :a else goto :end
:end</langsyntaxhighlight>
 
<langsyntaxhighlight lang=ProDOS>IGNORELINE Note: This example does not use the math module.
:a
editvar /newvar /value=a /title=Enter first integer:
Line 4,313:
editvar /newvar /value=d /title=Do you want to calculate more numbers?
if -d- /hasvalue yes goto :a else goto :end
:end</langsyntaxhighlight>
 
=={{header|Prolog}}==
Line 4,321:
Remainder (`rem`) matches the sign of its first operand.
 
<langsyntaxhighlight lang=prolog>
 
print_expression_and_result(M, N, Operator) :-
Line 4,333:
maplist( print_expression_and_result(M, N), [+,-,*,//,rem,^] ).
 
</syntaxhighlight>
</lang>
 
Use thus:
 
<langsyntaxhighlight lang=prolog>
?- arithmetic_integer.
|: 5.
Line 4,348:
5^7 is 78125
true.
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang=purebasic>OpenConsole()
Define a, b
Line 4,367:
Input()
CloseConsole()</langsyntaxhighlight>
 
=={{header|Python}}==
 
<langsyntaxhighlight lang=python>x = int(raw_input("Number 1: "))
y = int(raw_input("Number 2: "))
 
Line 4,384:
 
## Only used to keep the display up when the program ends
raw_input( )</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang=python>def getnum(prompt):
while True: # retrying ...
try:
Line 4,400:
x = getnum("Number1: ")
y = getnum("Number2: ")
...</langsyntaxhighlight>
 
(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 4,409:
 
=== Python 3.0 compatible code ===
<langsyntaxhighlight lang=python>def arithmetic(x, y):
for op in "+ - * // % **".split():
expr = "%(x)s %(op)s %(y)s" % vars()
Line 4,416:
 
arithmetic(12, 8)
arithmetic(input("Number 1: "), input("Number 2: "))</langsyntaxhighlight>
{{out}}
<pre>12 + 8 => 20
Line 4,434:
 
== Python 3.x Long Form ==
<langsyntaxhighlight lang=python>input1 = 18
# input1 = input()
input2 = 7
Line 4,454:
print("Actual Remainder: " + str(uu))
yy = input1 ** input2
print("Exponentiation: " + str(yy))</langsyntaxhighlight>
 
{{Out}}
Line 4,468:
=={{header|QB64}}==
''CBTJD'': 2020/03/12
<langsyntaxhighlight lang=vb>START:
INPUT "Enter two integers (a,b):"; a!, b!
IF a = 0 THEN END
Line 4,487:
IF UCASE$(a$) = "Y" THEN CLS: GOTO START
CLS
END</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
<langsyntaxhighlight lang=Quackery > $ "Please enter two integers separated by a space. "
input quackery
2dup say "Their sum is: " + echo cr
Line 4,501:
cr
say "Quotient rounds towards negative infinity." cr
say "Remainder matches the sign of the second argument."</langsyntaxhighlight>
 
{{Out}}
Line 4,515:
 
=={{header|R}}==
<langsyntaxhighlight lang=R>cat("insert number ")
a <- scan(nmax=1, quiet=TRUE)
cat("insert number ")
Line 4,525:
print(paste('a%%b=', a%%b))
print(paste('a^b=', a^b))
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
<langsyntaxhighlight lang=racket>
#lang racket/base
 
Line 4,536:
 
(arithmetic 8 12)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,556:
 
Note that <code>div</code> <b>requires</b> integer arguments. If you want integer division with other types, say <code>floor($a/$b)</code>.
<langsyntaxhighlight lang=perl6>my Int $a = get.floor;
my Int $b = get.floor;
 
Line 4,564:
say 'integer quotient: ', $a div $b;
say 'remainder: ', $a % $b;
say 'exponentiation: ', $a**$b;</langsyntaxhighlight>
 
=={{header|Raven}}==
 
<langsyntaxhighlight lang=raven>' Number 1: ' print expect 0 prefer as x
' Number 2: ' print expect 0 prefer as y
 
Line 4,575:
x y * " product: %d\n" print
x y / " quotient: %d\n" print
x y % " remainder: %d\n" print</langsyntaxhighlight>
 
=={{header|REBOL}}==
<langsyntaxhighlight lang=rebol>REBOL [
Title: "Integer"
URL: http://rosettacode.org/wiki/Arithmetic/Integer
Line 4,628:
]
 
print ["Exponentiation:" x ** y]</langsyntaxhighlight>
 
{{out}}
Line 4,650:
=={{header|Relation}}==
There is no input, variables have to be set in code. Format is there only for output.
<langsyntaxhighlight lang=Relation>
set a = -17
set b = 4
Line 4,659:
echo "a MOD b = ".format(a mod b,"%1d")
echo "a^b = ".format(pow(a,b),"%1d")
</syntaxhighlight>
</lang>
 
=={{header|ReScript}}==
 
<langsyntaxhighlight lang=ReScript>let a = int_of_string(Sys.argv[2])
let b = int_of_string(Sys.argv[3])
 
Line 4,676:
Js.log("a * b = " ++ string_of_int(product))
Js.log("a / b = " ++ string_of_int(division))
Js.log("a % b = " ++ string_of_int(remainder))</langsyntaxhighlight>
 
{{out}}
Line 4,692:
Retro's arithmetic functions are based on those in [[Forth]]. The example is an adaption of the one from Forth.
<langsyntaxhighlight lang=Retro>:arithmetic (ab-)
over '\na_______=_%n s:put
dup '\nb_______=_%n s:put
Line 4,699:
dup-pair * '\na_*_b___=_%n s:put
/mod '\na_/_b___=_%n s:put
'\na_mod_b_=_%n\n" s:put ;</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 4,707:
For division that produces a floating point number, the result is rounded to the nearest number that can be expressed
<br>within the current number of decimal digits &nbsp; (in the example program below, it is &nbsp; '''20''' &nbsp; decimal digits).
<langsyntaxhighlight lang=rexx>/*REXX program obtains two integers from the C.L. (a prompt); displays some operations.*/
numeric digits 20 /*#s are round at 20th significant dig.*/
parse arg x y . /*maybe the integers are on the C.L. */
Line 4,730:
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</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 4 &nbsp; -17 </tt>}}
<pre>
Line 4,751:
 
=={{header|Ring}}==
<langsyntaxhighlight lang=ring>
func Test a,b
see "a+b" + ( a + b ) + nl
Line 4,761:
see "a%b" + ( a % b ) + nl
see "a**b" + pow(a,b ) + nl
</syntaxhighlight>
</lang>
 
=={{header|Robotic}}==
<langsyntaxhighlight lang=robotic>
input string "Enter number 1:"
set "a" to "input"
Line 4,776:
[ "Remainder: ('a' % 'b')"
[ "Exponentiation: ('a'^'b')"
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
 
<langsyntaxhighlight lang=ruby>puts 'Enter x and y'
x = gets.to_i # to check errors, use x=Integer(gets)
y = gets.to_i
Line 4,790:
"Quotient: #{x.fdiv(y)}", # float
"Remainder: #{x%y}", # same sign as second operand
"Exponentiation: #{x**y}"</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang=runbasic>input "1st integer: "; i1
input "2nd integer: "; i2
Line 4,801:
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</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang=rust>use std::env;
 
fn main() {
Line 4,818:
println!("integer quotient: {}", a / b); // truncates towards zero
println!("remainder: {}", a % b); // same sign as first operand
}</langsyntaxhighlight>
 
=={{header|Sass/SCSS}}==
 
<langsyntaxhighlight lang=coffeescript>
@function arithmetic($a,$b) {
@return $a + $b, $a - $b, $a * $b, ($a - ($a % $b))/$b, $a % $b;
}
</syntaxhighlight>
</lang>
Which you use with:
<langsyntaxhighlight lang=coffeescript>
nth(arithmetic(10,3),1);
</syntaxhighlight>
</lang>
Or each of the functions separately:
<langsyntaxhighlight lang=coffeescript>
@function sum($a,$b) {
@return $a + $b;
Line 4,856:
@return $a / $b;
}
</syntaxhighlight>
</lang>
 
=={{header|Scala}}==
<langsyntaxhighlight lang=scala>val a = Console.readInt
val b = Console.readInt
Line 4,867:
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</langsyntaxhighlight>
 
=={{header|Scheme}}==
 
<langsyntaxhighlight lang=scheme>(define (arithmetic x y)
(for-each (lambda (op)
(write (list op x y))
Line 4,879:
'(+ - * / quotient remainder modulo max min gcd lcm)))
(arithmetic 8 12)</langsyntaxhighlight>
quotient - truncates towards 0
remainder - same sign as first operand
Line 4,899:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang=seed7>$ include "seed7_05.s7i";
 
const proc: main is func
Line 4,918:
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;</langsyntaxhighlight>
 
=={{header|SenseTalk}}==
<langsyntaxhighlight lang=sensetalk>ask "Enter the first number:"
put it into number1
 
Line 4,932:
put "Integer quotient: " & number1 div number2 -- Rounding towards 0
put "Remainder: " & number1 rem number2
put "Exponentiation: " & number1 to the power of number2</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang=ruby>var a = Sys.scanln("First number: ").to_i;
var b = Sys.scanln("Second number: ").to_i;
 
%w'+ - * // % ** ^ | & << >>'.each { |op|
"#{a} #{op} #{b} = #{a.$op(b)}".say;
}</langsyntaxhighlight>
 
{{out}}
Line 4,960:
 
=={{header|Slate}}==
<langsyntaxhighlight lang=slate>[| :a :b |
inform: (a + b) printString.
inform: (a - b) printString.
Line 4,968:
inform: (a \\ b) printString.
 
] applyTo: {Integer readFrom: (query: 'Enter a: '). Integer readFrom: (query: 'Enter b: ')}.</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<langsyntaxhighlight lang=smalltalk>| a b |
'Input number a: ' display.
a := (stdin nextLine) asInteger.
Line 4,981:
('a*b=%1' % { a * b }) displayNl.
('a/b=%1' % { a // b }) displayNl.
('a%%b=%1' % { a \\ b }) displayNl.</langsyntaxhighlight>
 
{{works with|Smalltalk/X}} (and all other Smalltalks)
<langsyntaxhighlight lang=smalltalk>|a b|
a := (Dialog request:'Enter first number:') asNumber.
b := (Dialog request:'Enter second number:') asNumber.
Line 4,991:
result := a perform:operator with:b.
'%P %s %P => %P\n' printf:{a . operator . b . result} on:Transcript
].</langsyntaxhighlight>
/ is exact division
<br>// is truncating division (towards negative infinity)
Line 5,042:
 
=={{header|smart BASIC}}==
<langsyntaxhighlight lang=qbasic>INPUT "Enter first number.":first
INPUT "Enter second number.":second
PRINT "The sum of";first;"and";second;"is ";first+second&"."
Line 5,053:
ENDIF
PRINT "The remainder being...";first%second&"."
PRINT STR$(first);"raised to the power of";second;"is ";first^second&"."</langsyntaxhighlight>
 
'''NOTES:''' Some curious aspects of smart BASIC to note in this code example:
Line 5,062:
 
=={{header|SNOBOL4}}==
<langsyntaxhighlight lang=snobol4>
output = "Enter first integer:"
first = input
Line 5,073:
output = "rem = " first - (qout * second)
output = "expo = " first ** second
end</langsyntaxhighlight>
 
=={{header|SNUSP}}==
Line 5,079:
 
''See also: [[Ethiopian Multiplication]]''
<langsyntaxhighlight lang=SNUSP>$\
,
@
Line 5,136:
\=@@@+@+++++#
.
#</langsyntaxhighlight>
 
=={{header|SQL}}==
{{works with|Oracle}}
<langsyntaxhighlight lang=sql>
-- test.sql
-- Tested in SQL*plus
Line 5,161:
 
select power(a,b) exponentiation from test;
</syntaxhighlight>
</lang>
 
<pre>
Line 5,210:
=={{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.
<langsyntaxhighlight lang=ssem>00101000000000100000000000000000 0. -20 to c
10100000000001100000000000000000 1. c to 5
10100000000000100000000000000000 2. -5 to c
10101000000000010000000000000000 3. Sub. 21
00000000000001110000000000000000 4. Stop
00000000000000000000000000000000 5. 0</langsyntaxhighlight>
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.
<langsyntaxhighlight lang=ssem>00101000000000100000000000000000 0. -20 to c
10101000000000010000000000000000 1. Sub. 21
10100000000001100000000000000000 2. c to 5
10100000000000100000000000000000 3. -5 to c
00000000000001110000000000000000 4. Stop
00000000000000000000000000000000 5. 0</langsyntaxhighlight>
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}}==
<langsyntaxhighlight lang=sml>val () = let
val a = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn)))
val b = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn)))
Line 5,238:
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</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang=swift>
let a = 6
let b = 4
Line 5,251:
print("Remainder = (a%b)")
print("No operator for Exponential")
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang=tcl>puts "Please enter two numbers:"
 
set x [expr {int([gets stdin])}]; # Force integer interpretation
Line 5,264:
puts "$x / $y = [expr {$x / $y}]"
puts "$x mod $y = [expr {$x % $y}]"
puts "$x 'to the' $y = [expr {$x ** $y}]"</langsyntaxhighlight>
 
Since Tcl doesn't really know about the "type" of a variable, the "<tt>expr</tt>" command is used to declare whatever follows as an "expression". This means there is no such thing as "integer arithmetic" and hence the kludge with <tt>int([gets&nbsp;stdin])</tt>.
Line 5,270:
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 =tcl>incr x $y</langsyntaxhighlight>
 
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].
Line 5,276:
=={{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.......
<langsyntaxhighlight lang=terraform>
#Aamrun, 15th August 2022
 
Line 5,306:
value = var.a % var.b
}
</syntaxhighlight>
</lang>
The floor function rounds to the closest lowest integer. Invocation and output are as below :
{{out}}
Line 5,335:
=={{header|TI-83 BASIC}}==
Pauses added due to TI-83's lack of screen size.
<langsyntaxhighlight lang=ti83b>
Prompt A,B
Disp "SUM"
Line 5,347:
Disp "REMAINDER"
Pause A-B*int(A/B)
</syntaxhighlight>
</lang>
 
=={{header|TI-89 BASIC}}==
 
<langsyntaxhighlight lang=ti89b>Local a, b
Prompt a, b
Disp "Sum: " & string(a + b)
Line 5,357:
Disp "Product: " & string(a * b)
Disp "Integer quotient: " & string(intDiv(a, b))
Disp "Remainder: " & string(remain(a, b))</langsyntaxhighlight>
 
=={{header|Toka}}==
 
<langsyntaxhighlight lang=toka>[ ( a b -- )
2dup ." a+b = " + . cr
2dup ." a-b = " - . cr
2dup ." a*b = " * . cr
2dup ." a/b = " / . ." remainder " mod . cr
] is mathops</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang=tuscript>
$$ MODE TUSCRIPT
a=5
Line 5,378:
c=a/b
c=a%b
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,401:
{{works with|Bourne Shell}}
{{works with|Almquist SHell}}
<langsyntaxhighlight lang=bash>#!/bin/sh
read a; read b;
echo "a+b = " `expr $a + $b`
Line 5,407:
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</langsyntaxhighlight>
 
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 5,416:
{{works with|pdksh|5.2.14}}
{{works with|Z SHell}}
<langsyntaxhighlight lang=bash>#!/bin/sh
read a; read b;
echo "a+b = $((a+b))"
Line 5,422:
echo "a*b = $((a*b))"
echo "a/b = $((a/b))" # truncates towards 0
echo "a mod b = $((a%b))" # same sign as first operand</langsyntaxhighlight>
 
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}}==
<langsyntaxhighlight lang=ursa>#
# integer arithmetic
#
Line 5,443:
out "quot:\t" (int (/ x y)) endl console
# mod takes the sign of x
out "mod:\t" (int (mod x y)) endl console</langsyntaxhighlight>
 
Sample session:
Line 5,456:
 
=={{header|VBA}}==
<syntaxhighlight lang=vb>
<lang vb>
'Arithmetic - Integer
Sub RosettaArithmeticInt()
Line 5,474:
Next opr
End Sub
</syntaxhighlight>
</lang>
 
=={{header|VBScript}}==
Line 5,480:
 
===Implementation===
<langsyntaxhighlight lang=vb>option explicit
dim a, b
wscript.stdout.write "A? "
Line 5,496:
wscript.echo "a \ b=", a \ b
wscript.echo "a mod b=", a mod b
wscript.echo "a ^ b=", a ^ b</langsyntaxhighlight>
 
===Another Implementation===
Gives the same output for the same input. Inspired by Python version.
<langsyntaxhighlight lang=vb>option explicit
dim a, b
wscript.stdout.write "A? "
Line 5,513:
for each op in split("+ - * / \ mod ^", " ")
wscript.echo "a",op,"b=",eval( "a " & op & " b")
next</langsyntaxhighlight>
 
===Invocation===
Line 5,530:
 
=={{header|Vedit macro language}}==
<langsyntaxhighlight lang=vedit>#1 = Get_Num("Give number a: ")
#2 = Get_Num("Give number b: ")
Message("a + b = ") Num_Type(#1 + #2)
Line 5,536:
Message("a * b = ") Num_Type(#1 * #2)
Message("a / b = ") Num_Type(#1 / #2)
Message("a % b = ") Num_Type(#1 % #2)</langsyntaxhighlight>
 
 
=={{header|Verilog}}==
<langsyntaxhighlight lang=Verilog>module main;
integer a, b;
integer suma, resta, producto;
Line 5,565:
$finish ;
end
endmodule</langsyntaxhighlight>
 
=={{header|Vim Script}}==
<langsyntaxhighlight lang=vim>let a = float2nr(input("Number 1: ") + 0)
let b = float2nr(input("Number 2: ") + 0)
echo "\nSum: " . (a + b)
Line 5,577:
" The sign of the result of the remainder operation matches the sign of
" the first operand
echo "Remainder: " . (a % b)</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
<langsyntaxhighlight lang=vbnet>Imports System.Console
Module Module1
Sub Main
Line 5,593:
WriteLine("Exponent " & a ^ b)
End Sub
End Module</langsyntaxhighlight>
 
=={{header|Vlang}}==
<langsyntaxhighlight lang=go>// Arithmetic-integer in V
// Tectonics: v run arithmetic-integer.v
module main
Line 5,624:
println("no exponentiation operator")
println(" math.pow: pow(a,b) = ${math.pow(a,b)}")
}</langsyntaxhighlight>
 
{{out}}
Line 5,639:
 
=={{header|Wart}}==
<langsyntaxhighlight lang=python>a <- (read)
b <- (read)
prn "sum: " a+b
Line 5,647:
prn "integer quotient: " (int a/b)
prn "remainder: " a%b
prn "exponent: " a^b</langsyntaxhighlight>
 
=={{header|Wren}}==
Line 5,653:
 
The sign of the remainder operator '%' matches the sign of the first operand.
<langsyntaxhighlight lang=ecmascript>import "io" for Stdin, Stdout
System.write("first number: ")
Stdout.flush()
Line 5,665:
System.print("integer quotient: %((a / b).floor)")
System.print("remainder: %(a % b)")
System.print("exponentiation: %(a.pow(b))")</langsyntaxhighlight>
 
{{out}}
Line 5,682:
=={{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.
<langsyntaxhighlight lang=asm>arithm: mov cx, a
mov bx, b
xor dx, dx
Line 5,703:
mov remainder, dx
 
ret</langsyntaxhighlight>
 
=={{header|XLISP}}==
<langsyntaxhighlight lang=xlisp>(DEFUN INTEGER-ARITHMETIC ()
(DISPLAY "Enter two integers separated by a space.")
(NEWLINE)
Line 5,722:
(DISPLAY `(REMAINDER ,(REM A B))) ; takes sign of first operand
(NEWLINE)
(DISPLAY `(EXPONENTIATION ,(EXPT A B))))</langsyntaxhighlight>
 
=={{header|XPL0}}==
<langsyntaxhighlight lang=XPL0>include c:\cxpl\codes;
int A, B;
[A:= IntIn(0);
Line 5,734:
IntOut(0, A/B); CrLf(0); \truncates toward zero
IntOut(0, rem(0)); CrLf(0); \remainder's sign matches first operand (A)
]</langsyntaxhighlight>
 
=={{header|XSLT}}==
<langsyntaxhighlight lang=xml><xsl:template name="arithmetic">
<xsl:param name="a">5</xsl:param>
<xsl:param name="b">2</xsl:param>
Line 5,745:
<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></langsyntaxhighlight>
 
 
=={{header|Yabasic}}==
<langsyntaxhighlight lang=Yabasic>input "ingrese un numero? " a
input "ingrese otro numero? " b
 
Line 5,758:
print "modulo ", a, " % ", b, " = ", mod(a, b)
print "potencia ", a, " ^ ", b, " = ", (a ^ b)
end</langsyntaxhighlight>
 
 
=={{header|Yorick}}==
<langsyntaxhighlight lang=yorick>x = y = 0;
read, x, y;
write, "x + y =", x + y;
Line 5,769:
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</langsyntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang=zkl>x,y:=ask("Two ints: ").split(" ").apply("toInt");
println("x+y = ",x + y);
println("x-y = ",x - y);
Line 5,778:
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</langsyntaxhighlight>
 
=={{header|zonnon}}==
<langsyntaxhighlight lang=zonnon>
module Main;
var
Line 5,794:
writeln("remainder: ", i mod j);
end Main.
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 5,807:
 
=={{header|ZX Spectrum Basic}}==
<langsyntaxhighlight lang=zxbasic>5 LET a=5: LET b=3
10 PRINT a;" + ";b;" = ";a+b
20 PRINT a;" - ";b;" = ";a-b
Line 5,814:
50 PRINT a;" mod ";b;" = ";a-INT (a/b)*b
60 PRINT a;" to the power of ";b;" = ";a^b
</syntaxhighlight>
</lang>
10,327

edits