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

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

Also include the exponentiation operator if one exists.

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:$==$~$=${{~%#:end: }:u:=>{x{=>~*>{x<:2:-#:ter: }:ml:x->{x{=>~*>{x<:1:-#:ter:^:ml: }:ter:<: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>

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

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>

Perl 6

Works with: Rakudo version #21 "Seattle"

<lang perl6>my Int $a = floor $*IN.get; my Int $b = floor $*IN.get;

say 'sum: ', $a + $b; say 'difference: ', $a - $b; say 'product: ', $a * $b; say 'integer quotient: ', $a div $b; say 'remainder: ', $a % $b; say 'exponentiation: ', $a**$b;</lang>

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

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

?></lang>

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>

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>

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>

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

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

(define (arithmetic x y)

 (for ([op '(+ - * / quotient remainder modulo max min gcd lcm)])
   (displayln (~a (list op x y) " => " 
                  ((eval op (make-base-namespace)) 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

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" Author: oofoe Date: 2010-09-29 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>

Sample 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

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       = %d" puts
 dup     "\nb       = %d" puts
 2over + "\na + b   = %d" puts
 2over - "\na - b   = %d" puts
 2over * "\na * b   = %d" puts
 /mod    "\na / b   = %d" puts
         "\na mod b = %d\n" puts ;</lang>

REXX

<lang rexx>/*REXX pgm gets 2 integers from the C.L. or via prompt, shows some opers*/ numeric digits 20 /*all numbers are rounded at ··· */

                                      /*··· the 20th significant digit.*/

parse arg x y . /*maybe the integers are on C.L.?*/ if y== then do /*nope, then prompt user for 'em.*/

              say "─────Enter two integer values  (separated by blanks):"
              parse pull x y .
              end
    do 2                              /*show  A with B, then  B with A.*/
    say                               /*show blank line for eyeballing.*/
    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 'div remainder' , "//", x//y, '    [sign from 1st operand]'
    call show 'power'         , "**", x**y
    parse value  x y  with  y x       /*swap the two values & do again.*/
    end   /*2*/

exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────SHOW subroutine─────────────────────*/ show: parse arg what,oper,value,comment say right(what,25)' ' x center(oper,4) y ' ───► ' value comment return</lang> output when using the input of: 17 -4

                 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
            div remainder  17  //  -4  ───►  1     [sign from 1st operand]
                    power  17  **  -4  ───►  0.000011973036721303624238

                 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
            div remainder  -4  //  17  ───►  -4     [sign from 1st operand]
                    power  -4  **  17  ───►  -17179869184

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

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>

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>

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

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>

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>

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.

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>

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

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>

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>

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>