Arithmetic/Integer

From Rosetta Code
Task
Arithmetic/Integer
You are encouraged to solve this task according to the task description, using any language you may know.

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

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

Integer Operations
Arithmetic | Comparison

Boolean Operations
Bitwise | Logical

String Operations
Concatenation | Interpolation | Comparison | Matching

Memory Operations
Pointers & references | Addresses

Task

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

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


Don't include error handling.

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

For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.

0815

<lang 0815> |~>|~#:end:> <:61:x<:3d:=<:20:$==$~$=${~>%<:2c:~$<:20:~$ <:62:x<:3d:=<:20:$==$~$=${~>%<:a:~$$ <:61:x<:2b:=<:20:$==$~$=$<:62:x<:3d:=<:20:$==$~$=${x{x~>~>~+%<:a:~$ <:61:x<:2d:=<:20:$==$~$=$<:62:x<:3d:=<:20:$==$~$=${x{x~>~>~-%<:a:~$ <:61:x<:2a:=<:20:$==$~$=$<:62:x<:3d:=<:20:$==$~$=${x{x~>~>~*%<:a:~$ <:61:x<:2f:=<:20:$==$~$=$<:62:x<:3d:=<:20:$==$~$=${x{x~>~>~/%<:a:~$ <:61:x<:25:=<:20:$==$~$=$<:62:x<:3d:=<:20:$==$~$=${x{x~>~>~/=%<:a:~$ {~>>{x<:1:-^:u: <:61:x<:5e:=<:20:$==$~$$=$<:62:x<:3D:=<:20:$==$~$=$Template:~%

 end
 A = {ReadInt}
 B = {ReadInt}

in

 {ForAll
  ["A+B = "#A+B
   "A-B = "#A-B
   "A*B = "#A*B
   "A/B = "#A div B  %% truncates towards 0
   "remainder "#A mod B  %% has the same sign as A
   "A^B = "#{Pow A B}
  ]
  System.showInfo}</lang>

Panda

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

Output:
atan2 ( 3 7 ) => 0.40489178628508343 
divide ( 3 7 ) => 0.42857142857142855 
gt ( 3 7 ) => UNDEFINED! 
gte ( 3 7 ) => UNDEFINED! 
lt ( 3 7 ) => 3 
lte ( 3 7 ) => 3 
max ( 3 7 ) => 7 
min ( 3 7 ) => 3 
minus ( 3 7 ) => -4 
mod ( 3 7 ) => 3 
plus ( 3 7 ) => 10 
pow ( 3 7 ) => 2187

PARI/GP

Integer division with \ rounds to . There also exists the \/ round-to-nearest (ties to ) operator. Ordinary division / does not round but returns rationals if given integers with a non-integral quotient. <lang parigp>arith(a,b)={

 print(a+b);
 print(a-b);
 print(a*b);
 print(a\b);
 print(a%b);
 print(a^b);

};</lang>

Pascal

<lang pascal>program arithmetic(input, output)

var

a, b: integer;

begin

readln(a, b);
writeln('a+b = ', a+b);
writeln('a-b = ', a-b);
writeln('a*b = ', a*b);
writeln('a/b = ', a div b, ', remainder ', a mod b);
writeln('a^b = ',Power(a,b):4:2);    {real power}
writeln('a^b = ',IntPower(a,b):4:2); {integer power}

end.</lang>

Perl

Works with: Perl version 5.x

<lang perl>my $a = <>; my $b = <>;

print

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

Phix

Library: Phix/pGUI
Library: Phix/online

You can run this online here (layout/space is not perfected yet).

with javascript_semantics
include pGUI.e

Ihandle lab, tab, res, dlg

constant fmt = """
a = %d
b = %d
a + b = %d
a - b = %d
a * b = %d
a / b = %g  (does not truncate)
remainder(a,b) = %d (same sign as first operand)
power(a,b) = %g
"""

function valuechanged_cb(Ihandle tab)
    string s = IupGetAttribute(tab,"VALUE")
    sequence r = scanf(s,"%d %d")
    if length(r)=1 then
        integer {a,b} = r[1]
        s = sprintf(fmt, {a, b, a+b, a-b, a*b, a/b, remainder(a,b), power(a,b)})
        IupSetStrAttribute(res,"TITLE",s)
        IupRefresh(res)
    end if
    return IUP_DEFAULT
end function

procedure main()
    IupOpen()
    lab = IupLabel("Enter two numbers")
    tab = IupText("VALUECHANGED_CB", Icallback("valuechanged_cb"),"EXPAND=HORIZONTAL")
    res = IupLabel("(separated by a space)\n\n\n\n\n\n\n","EXPAND=BOTH")
    dlg = IupDialog(IupVbox({IupHbox({lab,tab},"GAP=10,NORMALIZESIZE=VERTICAL"),
                             IupHbox({res})},"MARGIN=5x5"),
                            `SIZE=188x112,TITLE="Arithmetic/Integer"`)
    IupShow(dlg)
    if platform()!=JS then
        IupMainLoop()
        IupClose()
    end if
end procedure
 
main()
Output:

With an input of "2 3"

a = 2
b = 3
a + b = 5
a - b = -1
a * b = 6
a / b = 0.666667  (does not truncate)
remainder(a,b) = 2 (same sign as first operand)
power(a,b) = 8

Phixmonti

<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</lang>

PHL

<lang phl>module arith;

extern printf; extern scanf;

@Integer main [ @Pointer<@Integer> a = alloc(4); @Pointer<@Integer> b = alloc(4); scanf("%i %i", a, b);

printf("a + b = %i\n", a::get + b::get); printf("a - b = %i\n", a::get - b::get); printf("a * b = %i\n", a::get * b::get); printf("a / b = %i\n", a::get / b::get); printf("a % b = %i\n", a::get % b::get); printf("a ** b = %i\n", a::get ** b::get);

return 0; ]</lang>

PHP

<lang php><?php $a = fgets(STDIN); $b = fgets(STDIN);

echo

   "sum:                 ", $a + $b, "\n",
   "difference:          ", $a - $b, "\n",
   "product:             ", $a * $b, "\n",
   "truncating quotient: ", (int)($a / $b), "\n",
   "flooring quotient:   ", floor($a / $b), "\n",
   "remainder:           ", $a % $b, "\n",
   "power:               ", $a ** $b, "\n"; // PHP 5.6+ only

?></lang>

Picat

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

</lang>

Output:
2 3
2 + 3 = 5
2 - 3 = -1
2 * 3 = 6
2 div 3 = 0
2 rem 3 = 2

PicoLisp

<lang PicoLisp>(de math (A B)

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

Piet



command   stack
in(int)   A
duplicate AA
duplicate AAA
duplicate AAAA
duplicate AAAAA
in(int)   BAAAAA
duplicate BBAAAAA
duplicate BBBAAAAA
duplicate BBBBAAAAA
duplicate BBBBBAAAAA
push 9    9BBBBBAAAAA
push 1    19BBBBBAAAAA
roll      BBBBAAAABA
push 7    7BBBBAAAABA
push 1    17BBBBAAAABA
roll      BBBAAABABA
push 5    5BBBAAABABA
push 1    15BBBAAABABA
roll      BBAABABABA
push 3    3BBAABABABA
push 1    13BBAABABABA
roll      BABABABABA
add       (A+B)BABABABA
out(int)  BABABABA
sub       (A-B)BABABA
out(int)  BABABA
mult      (A*B)BABA
out(int)  BABA
divide    (A/B)BA
out(int)  BA
mod       (A%B)
out(int)  NULL
push 1    1
exit

How rounding is handled is up to the interpreter, but I believe the intent was round towards 0.

PL/I

<lang PL/I> get list (a, b); put skip list (a+b); put skip list (a-b); put skip list (a*b); put skip list (trunc(a/b)); /* truncates towards zero. */ put skip list (mod(a, b)); /* Remainder is always positive. */ put skip list (rem(a, b)); /* Sign can be negative. */</lang>

Plain English

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

Output:
Enter a number: 44
Enter another number: 3
47 is the sum.
41 is the difference.
132 is the product.
14 is the quotient.
2 is the remainder.
85184 is the power.

Pop11

<lang pop11>;;; Setup token reader vars itemrep; incharitem(charin) -> itemrep;

read the numbers

lvars a = itemrep(), b = itemrep();

Print results

printf(a + b, 'a + b = %p\n'); printf(a - b, 'a - b = %p\n'); printf(a * b, 'a * b = %p\n'); printf(a div b, 'a div b = %p\n'); printf(a mod b, 'a mod b = %p\n');</lang>

PostScript

<lang ps>/arithInteger {

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

} def</lang>

PowerShell

<lang powershell>$a = [int] (Read-Host First Number) $b = [int] (Read-Host Second Number)

Write-Host "Sum: $($a + $b)" Write-Host "Difference: $($a - $b)" Write-Host "Product: $($a * $b)" Write-Host "Quotient: $($a / $b)" Write-Host "Quotient, round to even: $([Math]::Round($a / $b))" Write-Host "Remainder, sign follows first: $($a % $b)"</lang> Numbers are automatically converted to accomodate for the result. This means not only that Int32 will be expanded to Int64 but also that a non-integer quotient will cause the result to be of a floating-point type.

The remainder has the sign of the first operand.

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

Processing

<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</lang>

Output:
7 + 5 = 12
7 - 5 = 2
7 * 5 = 35
7 / 5 = 1
7 % 5 = 2

ProDOS

<lang ProDOS>IGNORELINE Note: This example includes the math module. include arithmeticmodule

a

editvar /newvar /value=a /title=Enter first integer: editvar /newvar /value=b /title=Enter second integer: editvar /newvar /value=c do add -a-,-b-=-c- printline -c- do subtract a,b printline -c- do multiply a,b printline -c- do divide a,b printline -c- do modulus a,b printline -c- editvar /newvar /value=d /title=Do you want to calculate more numbers? if -d- /hasvalue yes goto :a else goto :end

end</lang>

<lang ProDOS>IGNORELINE Note: This example does not use the math module.

a

editvar /newvar /value=a /title=Enter first integer: editvar /newvar /value=b /title=Enter second integer: editvar /newvar /value=-a-+-b-=-c- printline -c- editvar /newvar /value=a*b=c printline -c- editvar /newvar /value=a/b=c printline -c- editvar /newvar /value=a %% b=c printline -c- editvar /newvar /value=d /title=Do you want to calculate more numbers? if -d- /hasvalue yes goto :a else goto :end

end</lang>

Prolog

Integer quotient (`//`) rounds towards 0.

Remainder (`rem`) matches the sign of its first operand.

<lang prolog>

print_expression_and_result(M, N, Operator) :-

   Expression =.. [Operator, M, N],
   Result is Expression,
   format('~w ~8|is ~d~n', [Expression, Result]).

arithmetic_integer :-

   read(M),
   read(N),
   maplist( print_expression_and_result(M, N), [+,-,*,//,rem,^] ).

</lang>

Use thus:

<lang prolog> ?- arithmetic_integer. |: 5. |: 7. 5+7 is 12 5-7 is -2 5*7 is 35 5//7 is 0 5 rem 7 is 5 5^7 is 78125 true. </lang>

PureBasic

<lang purebasic>OpenConsole()

Define a, b

Print("Number 1: "): a = Val(Input()) Print("Number 2: "): b = Val(Input())

PrintN("Sum: " + Str(a + b)) PrintN("Difference: " + Str(a - b)) PrintN("Product: " + Str(a * b)) PrintN("Quotient: " + Str(a / b)) ; Integer division (rounding mode=truncate) PrintN("Remainder: " + Str(a % b)) PrintN("Power: " + Str(Pow(a, b)))

Input()

CloseConsole()</lang>

Python

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

print "Sum: %d" % (x + y) print "Difference: %d" % (x - y) print "Product: %d" % (x * y) print "Quotient: %d" % (x / y) # or x // y for newer python versions.

                                  # truncates towards negative infinity

print "Remainder: %d" % (x % y) # same sign as second operand print "Quotient: %d with Remainder: %d" % divmod(x, y) print "Power: %d" % x**y

    1. Only used to keep the display up when the program ends

raw_input( )</lang>

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

<lang python>def getnum(prompt):

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

x = getnum("Number1: ") y = getnum("Number2: ") ...</lang>

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

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

quotient, remainder = divmod(355,113)

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

Python 3.0 compatible code

<lang python>def arithmetic(x, y):

   for op in "+ - * // % **".split():
       expr = "%(x)s %(op)s %(y)s" % vars()
       print("%s\t=> %s" % (expr, eval(expr)))


arithmetic(12, 8) arithmetic(input("Number 1: "), input("Number 2: "))</lang>

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

Python 3.x Long Form

<lang python>input1 = 18

  1. input1 = input()

input2 = 7

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

  1. print(tt)

print("Whole Remainder: " + str(int(uu))) print("Actual Remainder: " + str(uu)) yy = input1 ** input2 print("Exponentiation: " + str(yy))</lang>

Output:
Sum: 		  25
Difference: 	  11
Product: 	  126
Integer quotient: 2
Float quotient:   2.5714285714285716
Whole Remainder:  5
Actual Remainder: 5.714285714285716
Exponentiation:   612220032

QB64

CBTJD: 2020/03/12 <lang vb>START: INPUT "Enter two integers (a,b):"; a!, b! IF a = 0 THEN END IF b = 0 THEN

   PRINT "Second integer is zero. Zero not allowed for Quotient or Remainder."
   GOTO START

END IF PRINT PRINT " Sum = "; a + b PRINT " Difference = "; a - b PRINT " Product = "; a * b ' Notice the use of the INTEGER Divisor "\" as opposed to the regular divisor "/". PRINT "Integer Quotient = "; a \ b, , "* Rounds toward 0." PRINT " Remainder = "; a MOD b, , "* Sign matches first operand." PRINT " Exponentiation = "; a ^ b PRINT INPUT "Again? (y/N)"; a$ IF UCASE$(a$) = "Y" THEN CLS: GOTO START CLS END</lang>

Quackery

<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."</lang>
Output:
Please enter two integers separated by a space. 543 21
Their sum is: 564
Their difference is: 522
Their product is: 11403
Their integer quotient is: 25
Their remainder is: 18
Their exponentiation is: 2696475144200627485897267767746883957141292127831428752543

R

<lang R>cat("insert number ") a <- scan(nmax=1, quiet=TRUE) cat("insert number ") b <- scan(nmax=1, quiet=TRUE) print(paste('a+b=', a+b)) print(paste('a-b=', a-b)) print(paste('a*b=', a*b)) print(paste('a%/%b=', a%/%b)) print(paste('a%%b=', a%%b)) print(paste('a^b=', a^b)) </lang>

Racket

<lang racket>

  1. lang racket/base

(define (arithmetic x y)

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

(arithmetic 8 12) </lang>

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

Raku

(formerly Perl 6)

Note that div requires integer arguments. If you want integer division with other types, say floor($a/$b). <lang perl6>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;</lang>

Raven

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

x y + " sum: %d\n" print x y - "difference: %d\n" print x y * " product: %d\n" print x y / " quotient: %d\n" print x y % " remainder: %d\n" print</lang>

REBOL

<lang rebol>REBOL [ Title: "Integer" URL: http://rosettacode.org/wiki/Arithmetic/Integer ]

x: to-integer ask "Please type in an integer, and press [enter]: " y: to-integer ask "Please enter another integer: " print ""

print ["Sum:" x + y] print ["Difference:" x - y] print ["Product:" x * y]

print ["Integer quotient (coercion)  :" to-integer x / y] print ["Integer quotient (away from zero)  :" round x / y] print ["Integer quotient (halves round towards even digits)  :" round/even x / y] print ["Integer quotient (halves round towards zero)  :" round/half-down x / y] print ["Integer quotient (round in negative direction)  :" round/floor x / y] print ["Integer quotient (round in positive direction)  :" round/ceiling x / y] print ["Integer quotient (halves round in positive direction):" round/half-ceiling x / y]

print ["Remainder:" r: x // y]

REBOL evaluates infix expressions from left to right. There are no
precedence rules -- whatever is first gets evaluated. Therefore when
performing this comparison, I put parens around the first term
("sign? a") of the expression so that the value of /a/ isn't
compared to the sign of /b/. To make up for it, notice that I don't
have to use a specific return keyword. The final value in the
function is returned automatically.

match?: func [a b][(sign? a) = sign? b]

result: copy [] if match? r x [append result "first"] if match? r y [append result "second"]

You can evaluate arbitrary expressions in the middle of a print, so
I use a "switch" to provide a more readable result based on the
length of the /results/ list.

print [ "Remainder sign matches:" switch length? result [ 0 ["neither"] 1 [result/1] 2 ["both"] ] ]

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

Output:
Please type in an integer, and press [enter]: 17
Please enter another integer: -4

Sum: 13
Difference: 21
Product: -68
Integer quotient (coercion)                          : -4
Integer quotient (away from zero)                    : -4
Integer quotient (halves round towards even digits)  : -4
Integer quotient (halves round towards zero)         : -4
Integer quotient (round in negative direction)       : -5
Integer quotient (round in positive direction)       : -4
Integer quotient (halves round in positive direction): -4
Remainder: 1
Remainder sign matches: first
Exponentiation: 1.19730367213036E-5

Relation

There is no input, variables have to be set in code. Format is there only for output. <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") </lang>

ReScript

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

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

Retro

Retro's arithmetic functions are based on those in Forth. The example is an adaption of the one from Forth.

<lang Retro>:arithmetic (ab-)

 over       '\na_______=_%n s:put
 dup        '\nb_______=_%n s:put
 dup-pair + '\na_+_b___=_%n s:put
 dup-pair - '\na_-_b___=_%n s:put
 dup-pair * '\na_*_b___=_%n s:put
 /mod       '\na_/_b___=_%n s:put
            '\na_mod_b_=_%n\n" s:put ;</lang>

REXX

All operators automatically produce integers where appropriate   (up to twenty decimal digits in the program below),
or numbers in exponential format when necessary.   (The REXX default is   9   decimal digits.)

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

 do while \datatype(x,'W') | \datatype(y,'W')   /*both   X  and  Y   must be integers. */
 say "─────Enter two integer values  (separated by blanks):"
 parse pull x y .                               /*accept two thingys from command line.*/
 end   /*while*/
                                                /* [↓]  perform this  DO  loop twice.  */
    do j=1  for 2                               /*show  A  oper  B,   then  B  oper  A.*/
    call show 'addition'          ,  "+",   x+y
    call show 'subtraction'       ,  "-",   x-y
    call show 'multiplication'    ,  "*",   x*y
    call show 'int  division'     ,  "%",   x%y,  '    [rounds down]'
    call show 'real division'     ,  "/",   x/y
    call show 'division remainder',  "//",  x//y, '    [sign from 1st operand]'
    call show 'power'             ,  "**",  x**y
    parse value  x  y    with    y  x           /*swap the two values and perform again*/
    if j==1  then say copies('═', 79)           /*display a fence after the 1st round. */
    end   /*j*/

exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ show: parse arg c,o,#,?; say right(c,25)' ' x center(o,4) y " ───► " #  ?; return</lang>

output   when using the input of:     4   -17
                 addition  4  +   -17  ───►  -13
              subtraction  4  -   -17  ───►  21
           multiplication  4  *   -17  ───►  -68
            int  division  4  %   -17  ───►  0     [rounds down]
            real division  4  /   -17  ───►  -0.23529411764705882353
       division remainder  4  //  -17  ───►  4     [sign from 1st operand]
                    power  4  **  -17  ───►  5.8207660913467407227E-11
═══════════════════════════════════════════════════════════════════════════════
                 addition  -17  +   4  ───►  -13
              subtraction  -17  -   4  ───►  -21
           multiplication  -17  *   4  ───►  -68
            int  division  -17  %   4  ───►  -4     [rounds down]
            real division  -17  /   4  ───►  -4.25
       division remainder  -17  //  4  ───►  -1     [sign from 1st operand]
                    power  -17  **  4  ───►  83521

Ring

<lang ring> func Test a,b

  see "a+b" + ( a + b ) + nl
  see "a-b" + ( a - b ) + nl
  see "a*b" + ( a * b ) + nl
  // The quotient isn't integer, so we use the Ceil() function, which truncates it downward.
  see "a/b" + Ceil( a / b ) + nl
  // Remainder:
  see "a%b" + ( a % b ) + nl
  see "a**b" +  pow(a,b )  + nl

</lang>

Robotic

<lang robotic> input string "Enter number 1:" set "a" to "input" input string "Enter number 2:" set "b" to "input"

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

Ruby

<lang ruby>puts 'Enter x and y' x = gets.to_i # to check errors, use x=Integer(gets) y = gets.to_i

puts "Sum: #{x+y}",

    "Difference: #{x-y}",
    "Product: #{x*y}",
    "Quotient: #{x/y}",       # truncates towards negative infinity
    "Quotient: #{x.fdiv(y)}", # float
    "Remainder: #{x%y}",      # same sign as second operand
    "Exponentiation: #{x**y}"</lang>

Run BASIC

<lang runbasic>input "1st integer: "; i1 input "2nd integer: "; i2

print " Sum"; i1 + i2 print " Diff"; i1 - i2 print " Product"; i1 * i2 if i2 <>0 then print " Quotent "; int( i1 / i2); else print "Cannot divide by zero." print "Remainder"; i1 MOD i2 print "1st raised to power of 2nd"; i1 ^ i2</lang>

Rust

Note that this code cannot be run within the Rust playpen as it does not support console input. <lang rust>use std::env;

fn main() {

   let args: Vec<_> = env::args().collect();
   let a = args[1].parse::<i32>().unwrap();
   let b = args[2].parse::<i32>().unwrap();
   println!("sum:              {}", a + b);
   println!("difference:       {}", a - b);
   println!("product:          {}", a * b);
   println!("integer quotient: {}", a / b); // truncates towards zero
   println!("remainder:        {}", a % b); // same sign as first operand

}</lang>

Sass/SCSS

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

@function difference($a,$b) { @return $a - $b; }

@function product($a,$b) { @return $a * $b; }

@function integer-division($a,$b) { @return ($a - ($a % $b))/$b; }

@function remainder($a,$b) { @return $a % $b; }

@function float-division($a,$b) { @return $a / $b; } </lang>

Scala

<lang scala>val a = Console.readInt val b = Console.readInt

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

Scheme

<lang scheme>(define (arithmetic x y)

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

(arithmetic 8 12)</lang> quotient - truncates towards 0 remainder - same sign as first operand modulo - same sign as second operand

 prints this:

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

Seed7

<lang seed7>$ include "seed7_05.s7i";

const proc: main is func

 local
   var integer: a is 0;
   var integer: b is 0;
 begin
   write("a = ");
   readln(a);
   write("b = ");
   readln(b);

   writeln("a + b = " <& a + b);
   writeln("a - b = " <& a - b);
   writeln("a * b = " <& a * b);
   writeln("a div b = " <& a div b);    # Rounds towards zero
   writeln("a rem b = " <& a rem b);    # Sign of the first operand
   writeln("a mdiv b = " <& a mdiv b);  # Rounds towards negative infinity
   writeln("a mod b = " <& a mod b);    # Sign of the second operand
 end func;</lang>

SenseTalk

<lang sensetalk>ask "Enter the first number:" put it into number1

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

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

Sidef

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

}</lang>

Output:
First number: 1234
Second number: 7
1234 + 7 = 1241
1234 - 7 = 1227
1234 * 7 = 8638
1234 // 7 = 176
1234 % 7 = 2
1234 ** 7 = 4357186184021382204544
1234 ^ 7 = 1237
1234 | 7 = 1239
1234 & 7 = 2
1234 << 7 = 157952
1234 >> 7 = 9

Slate

<lang slate>[| :a :b | inform: (a + b) printString. inform: (a - b) printString. inform: (a * b) printString. inform: (a / b) printString. inform: (a // b) printString. inform: (a \\ b) printString.

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

Smalltalk

Works with: GNU Smalltalk

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

Works with: Smalltalk/X

(and all other Smalltalks)

<lang smalltalk>|a b| a := (Dialog request:'Enter first number:') asNumber. b := (Dialog request:'Enter second number:') asNumber.

  1. ( + - / * // \\ quo: rem: raisedTo: **) do:[:operator |
   |result|
   result := a perform:operator with:b.
   '%P %s %P => %P\n' printf:{a . operator . b . result} on:Transcript

].</lang> / is exact division
// is truncating division (towards negative infinity)
\\ is remainder from \\
quo: is truncating division (towards zero)
\\ is remainder from quo:
** is just an alias for raisedTo:

Entering 10 and 3, generates:

Output:
10 + 3 => 13
10 - 3 => 7
10 / 3 => (10/3)
10 * 3 => 30
10 // 3 => 3
10 \\ 3 => 1
10 quo: 3 => 3
10 rem: 3 => 1
10 raisedTo: 3 => 1000
10 ** 3 => 1000

Entering 10 and -3 generates:

Output:
10 + -3 => 7
10 - -3 => 13
10 / -3 => (-10/3)
10 * -3 => -30
10 // -3 => -4
10 \\ -3 => -2
10 quo: -3 => -3
10 rem: -3 => 1
10 raisedTo: -3 => (1/1000)
10 ** -3 => (1/1000)

Entering 20 and 50 generates (notice the fraction and the long integer results):

Output:
20 + 50 => 70
20 - 50 => -30
20 / 50 => (2/5)
20 * 50 => 1000
20 // 50 => 0
20 \\ 50 => 20
20 quo: 50 => 0
20 rem: 50 => 20
20 raisedTo: 50 => 112589990684262400000000000000000000000000000000000000000000000000
20 ** 50 => 112589990684262400000000000000000000000000000000000000000000000000

smart BASIC

<lang qbasic>INPUT "Enter first number.":first INPUT "Enter second number.":second PRINT "The sum of";first;"and";second;"is ";first+second&"." PRINT "The difference between";first;"and";second;"is ";ABS(first-second)&"." PRINT "The product of";first;"and";second;"is ";first*second&"." IF second THEN

   PRINT "The integer quotient of";first;"and";second;"is ";INTEG(first/second)&"."

ELSE

   PRINT "Division by zero not cool."

ENDIF PRINT "The remainder being...";first%second&"." PRINT STR$(first);"raised to the power of";second;"is ";first^second&"."</lang>

NOTES: Some curious aspects of smart BASIC to note in this code example:

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

SNOBOL4

<lang snobol4>

       output = "Enter first integer:"
 	first = input

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

SNUSP

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

See also: Ethiopian Multiplication <lang SNUSP>$\

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

SQL

Works with: Oracle

<lang sql> -- test.sql -- Tested in SQL*plus

drop table test;

create table test (a integer, b integer);

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

commit;

select a-b difference from test;

select a*b product from test;

select trunc(a/b) integer_quotient from test;

select mod(a,b) remainder from test;

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

SQL> @test.sql

Table dropped.


Table created.

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

1 row created.


Commit complete.


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


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


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


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


EXPONENTIATION
--------------
            81
   

SSEM

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

Standard ML

<lang sml>val () = let

 val a = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn)))
 val b = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn)))

in

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

end</lang>

Swift

<lang swift> let a = 6 let b = 4

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

Tcl

<lang tcl>puts "Please enter two numbers:"

set x [expr {int([gets stdin])}]; # Force integer interpretation set y [expr {int([gets stdin])}]; # Force integer interpretation

puts "$x + $y = [expr {$x + $y}]" puts "$x - $y = [expr {$x - $y}]" puts "$x * $y = [expr {$x * $y}]" puts "$x / $y = [expr {$x / $y}]" puts "$x mod $y = [expr {$x % $y}]" puts "$x 'to the' $y = [expr {$x ** $y}]"</lang>

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

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

<lang tcl>incr x $y</lang>

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

TI-83 BASIC

Pauses added due to TI-83's lack of screen size. <lang ti83b> Prompt A,B Disp "SUM" Pause A+B Disp "DIFFERENCE" Pause A-B Disp "PRODUCT" Pause AB Disp "INTEGER QUOTIENT" Pause int(A/B) Disp "REMAINDER" Pause A-B*int(A/B) </lang>

TI-89 BASIC

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

Toka

<lang toka>[ ( a b -- )

 2dup ." a+b = " + . cr  
 2dup ." a-b = " - . cr  
 2dup ." a*b = " * . cr  
 2dup ." a/b = " / . ." remainder " mod . cr  

] is mathops</lang>

TUSCRIPT

<lang tuscript> $$ MODE TUSCRIPT a=5 b=3 c=a+b c=a-b c=a*b c=a/b c=a%b </lang>

Output:
a=5
b=3
c=a+b
c            = 8
c=a-b
c            = 2
c=a*b
c            = 15
c=a/b
c            = 1
c=a%b
c            = 2

UNIX Shell

The Unix shell does not directly support arithmetic operations, so external tools, such as expr are used to perform arithmetic calculations when required:

Works with: Bourne Shell
Works with: Almquist SHell

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

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

With SUSv3 parameter expansions:

Works with: Bourne Again SHell version 3.2
Works with: pdksh version 5.2.14
Works with: Z SHell

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

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

Ursa

<lang ursa>#

  1. integer arithmetic

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

out "\nsum:\t" (int (+ x y)) endl console out "diff:\t" (int (- x y)) endl console out "prod:\t" (int (* x y)) endl console

  1. quotient doesn't round at all, but the int function rounds up

out "quot:\t" (int (/ x y)) endl console

  1. mod takes the sign of x

out "mod:\t" (int (mod x y)) endl console</lang>

Sample session:

number 1: 15
number 2: 7

sum:	22
diff:	8
prod:	105
quot:	2
mod:	1

VBA

<lang vb> 'Arithmetic - Integer Sub RosettaArithmeticInt() Dim opr As Variant, a As Integer, b As Integer On Error Resume Next

a = CInt(InputBox("Enter first integer", "XLSM | Arithmetic")) b = CInt(InputBox("Enter second integer", "XLSM | Arithmetic"))

Debug.Print "a ="; a, "b="; b, vbCr For Each opr In Split("+ - * / \ mod ^", " ")

   Select Case opr
       Case "mod":     Debug.Print "a mod b", a; "mod"; b, a Mod b
       Case "\":       Debug.Print "a \ b", a; "\"; b, a \ b
       Case Else:      Debug.Print "a "; opr; " b", a; opr; b, Evaluate(a & opr & b)
   End Select

Next opr End Sub </lang>

VBScript

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

Implementation

<lang vb>option explicit dim a, b wscript.stdout.write "A? " a = wscript.stdin.readline wscript.stdout.write "B? " b = wscript.stdin.readline

a = int( a ) b = int( b )

wscript.echo "a + b=", a + b wscript.echo "a - b=", a - b wscript.echo "a * b=", a * b wscript.echo "a / b=", a / b wscript.echo "a \ b=", a \ b wscript.echo "a mod b=", a mod b wscript.echo "a ^ b=", a ^ b</lang>

Another Implementation

Gives the same output for the same input. Inspired by Python version. <lang vb>option explicit dim a, b wscript.stdout.write "A? " a = wscript.stdin.readline wscript.stdout.write "B? " b = wscript.stdin.readline

a = int( a ) b = int( b )

dim op for each op in split("+ - * / \ mod ^", " ") wscript.echo "a",op,"b=",eval( "a " & op & " b") next</lang>

Invocation

C:\foo>arithmetic.vbs
A? 45
B? 11
a + b= 4511
a - b= 34
a * b= 495
a / b= 4.09090909090909
a \ b= 4
a mod b= 1
a ^ b= 1.5322783012207E+18

Vedit macro language

<lang vedit>#1 = Get_Num("Give number a: ")

  1. 2 = Get_Num("Give number b: ")

Message("a + b = ") Num_Type(#1 + #2) Message("a - b = ") Num_Type(#1 - #2) Message("a * b = ") Num_Type(#1 * #2) Message("a / b = ") Num_Type(#1 / #2) Message("a % b = ") Num_Type(#1 % #2)</lang>


Verilog

<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</lang>

Vim Script

<lang vim>let a = float2nr(input("Number 1: ") + 0) let b = float2nr(input("Number 2: ") + 0) echo "\nSum: " . (a + b) echo "Difference: " . (a - b) echo "Product: " . (a * b) " The result of an integer division is truncated echo "Quotient: " . (a / b) " The sign of the result of the remainder operation matches the sign of " the first operand echo "Remainder: " . (a % b)</lang>

Visual Basic .NET

<lang vbnet>Imports System.Console Module Module1

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

End Module</lang>

Vlang

<lang go>// Arithmetic-integer in V // 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)}")

}</lang>

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

Wart

<lang python>a <- (read) b <- (read) prn "sum: " a+b prn "difference: " a-b prn "product: " a*b prn "quotient: " a/b prn "integer quotient: " (int a/b) prn "remainder: " a%b prn "exponent: " a^b</lang>

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. <lang ecmascript>import "io" for Stdin, Stdout System.write("first number: ") Stdout.flush() var a = Num.fromString(Stdin.readLine()) System.write("second number: ") Stdout.flush() var b = Num.fromString(Stdin.readLine()) System.print("sum:  %(a + b)") System.print("difference:  %(a - b)") System.print("product:  %(a * b)") System.print("integer quotient: %((a / b).floor)") System.print("remainder:  %(a % b)") System.print("exponentiation:  %(a.pow(b))")</lang>

Output:

Sample input/output:

first number:     4
second number:    3
sum:              7
difference:       1
product:          12
integer quotient: 1
remainder:        1
exponentiation:   64

x86 Assembly

Input and output would be OS-specific and are not implemented. This routine works on the 16-bit 8086, as well as on its 32-bit and 64-bit successors: it could be trivially modified to perform 32-bit or 64-bit arithmetic on machines where those are supported. The quotient is truncated towards zero; the remainder takes its sign from the first operand. <lang asm>arithm: mov cx, a

       mov      bx,          b
       xor      dx,          dx
       
       mov      ax,          cx
       add      ax,          bx
       mov      sum,         ax
       
       mov      ax,          cx
       imul     bx
       mov      product,     ax
       
       mov      ax,          cx
       sub      ax,          bx
       mov      difference,  ax
       
       mov      ax,          cx
       idiv     bx
       mov      quotient,    ax
       mov      remainder,   dx
       ret</lang>

XLISP

<lang xlisp>(DEFUN INTEGER-ARITHMETIC ()

   (DISPLAY "Enter two integers separated by a space.")
   (NEWLINE)
   (DISPLAY "> ")
   (DEFINE A (READ))
   (DEFINE B (READ))
   (DISPLAY `(SUM ,(+ A B)))
   (NEWLINE)
   (DISPLAY `(DIFFERENCE ,(- A B)))
   (NEWLINE)
   (DISPLAY `(PRODUCT ,(* A B)))
   (NEWLINE)
   (DISPLAY `(QUOTIENT ,(QUOTIENT A B))) ; truncates towards zero
   (NEWLINE)
   (DISPLAY `(REMAINDER ,(REM A B))) ; takes sign of first operand
   (NEWLINE)
   (DISPLAY `(EXPONENTIATION ,(EXPT A B))))</lang>

XPL0

<lang XPL0>include c:\cxpl\codes; int A, B; [A:= IntIn(0);

B:= IntIn(0);

IntOut(0, A+B); CrLf(0); IntOut(0, A-B); CrLf(0); IntOut(0, A*B); CrLf(0); IntOut(0, A/B); CrLf(0); \truncates toward zero IntOut(0, rem(0)); CrLf(0); \remainder's sign matches first operand (A) ]</lang>

XSLT

<lang xml><xsl:template name="arithmetic">

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


Yabasic

<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</lang>


Yorick

<lang yorick>x = y = 0; read, x, y; write, "x + y =", x + y; write, "x - y =", x - y; write, "x * y =", x * y; write, "x / y =", x / y; // rounds toward zero write, "x % y =", x % y; // remainder; matches sign of first operand when operands' signs differ write, "x ^ y =", x ^ y; // exponentiation</lang>

zkl

<lang zkl>x,y:=ask("Two ints: ").split(" ").apply("toInt"); println("x+y = ",x + y); println("x-y = ",x - y); println("x*y = ",x * y); println("x/y = ",x / y); // 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</lang>

zonnon

<lang zonnon> module Main; var i,j: integer; begin write("A integer?:");readln(i); write("another?: ");readln(j); writeln("sum: ",i + j); writeln("difference: ", i - j); writeln("product: ", i * j); writeln("quotient: ", i div j); writeln("remainder: ", i mod j); end Main. </lang>

Output:
A integer?:2
another?: 3
sum:                    5
difference:                   -1
product:                    6
quotient:                    0
remainder:                    2

ZX Spectrum Basic

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