Modulo operation
Encyclopedia
In computing
Computing
Computing is usually defined as the activity of using and improving computer hardware and software. It is the computer-specific part of information technology...

, the modulo operation finds the remainder
Remainder
In arithmetic, the remainder is the amount "left over" after the division of two integers which cannot be expressed with an integer quotient....

 of division
Division (mathematics)
right|thumb|200px|20 \div 4=5In mathematics, especially in elementary arithmetic, division is an arithmetic operation.Specifically, if c times b equals a, written:c \times b = a\,...

 of one number by another.

Given two positive numbers, (the dividend
Dividend
Dividends are payments made by a corporation to its shareholder members. It is the portion of corporate profits paid out to stockholders. When a corporation earns a profit or surplus, that money can be put to two uses: it can either be re-invested in the business , or it can be distributed to...

) and (the divisor
Divisor
In mathematics, a divisor of an integer n, also called a factor of n, is an integer which divides n without leaving a remainder.-Explanation:...

), a modulo n (abbreviated as a mod n) can be thought of as the remainder, on division of a by n. For instance, the expression "5 mod 4" would evaluate to 1 because 5 divided by 4 leaves a remainder of 1, while "9 mod 3" would evaluate to 0 because the division of 9 by 3 leaves a remainder of 0; there is nothing to subtract from 9 after multiplying 3 times 3. (Notice that doing the division with a calculator won't show you the result referred to here by this operation, the quotient will be expressed as a decimal.) When either or is negative, this naive definition breaks down and programming languages differ in how these values are defined. Although typically performed with a and n both being integers, many computing systems allow other types of numeric operands. The range of numbers for an integer modulo of n is 0 to n - 1. (n mod 1 is always 0; n mod 0 is undefined, possibly resulting in a "Division by zero" error in computer programming languages) See modular arithmetic
Modular arithmetic
In mathematics, modular arithmetic is a system of arithmetic for integers, where numbers "wrap around" after they reach a certain value—the modulus....

 for an older and related convention applied in number theory
Number theory
Number theory is a branch of pure mathematics devoted primarily to the study of the integers. Number theorists study prime numbers as well...

.

Remainder calculation for the modulo operation

Integer modulo operators in various programming languages
Language Operator Result has the same sign as
ActionScript
ActionScript
ActionScript is an object-oriented language originally developed by Macromedia Inc. . It is a dialect of ECMAScript , and is used primarily for the development of websites and software targeting the Adobe Flash Player platform, used on Web pages in the form of...

 
% Dividend
Ada
Ada (programming language)
Ada is a structured, statically typed, imperative, wide-spectrum, and object-oriented high-level computer programming language, extended from Pascal and other languages...

mod Divisor
rem Dividend
ASP  Mod Not defined
ALGOL-68  Always positive
AMPL
AMPL
AMPL, an acronym for "A Mathematical Programming Language", is an algebraic modeling language for describing and solving high-complexity problems for large-scale mathematical computation AMPL, an acronym for "A Mathematical Programming Language", is an algebraic modeling language for describing and...

 
mod Dividend
AppleScript
AppleScript
AppleScript is a scripting language created by Apple Inc. and built into Macintosh operating systems since System 7. The term "AppleScript" may refer to the scripting system itself, or to particular scripts that are written in the AppleScript language....

 
mod Dividend
BASIC
BASIC
BASIC is a family of general-purpose, high-level programming languages whose design philosophy emphasizes ease of use - the name is an acronym from Beginner's All-purpose Symbolic Instruction Code....

 
Mod Not defined
bc
Bc programming language
bc, for bench calculator, is "an arbitrary precision calculator language" with syntax similar to the C programming language. bc is typically used as either a mathematical scripting language or as an interactive mathematical shell....

 
% Dividend
bash  % Dividend
C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

 (ISO 1990)
% Implementation defined
C (ISO 1999)
C99
C99 is a modern dialect of the C programming language. It extends the previous version with new linguistic and library features, and helps implementations make better use of available computer hardware and compiler technology.-History:...

 
% Dividend
C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

 
% Implementation defined
C#  % Dividend
CLARION  % Dividend
Clojure
Clojure
Clojure |closure]]") is a recent dialect of the Lisp programming language created by Rich Hickey. It is a general-purpose language supporting interactive development that encourages a functional programming style, and simplifies multithreaded programming....

 
mod Divisor
ColdFusion
ColdFusion
In computing, ColdFusion is the name of a commercial rapid application development platform invented by Jeremy and JJ Allaire in 1995. ColdFusion was originally designed to make it easier to connect simple HTML pages to a database, by version 2 it had...

 
% Dividend
Common Lisp
Common Lisp
Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in ANSI standard document ANSI INCITS 226-1994 , . From the ANSI Common Lisp standard the Common Lisp HyperSpec has been derived for use with web browsers...

mod Divisor
rem Dividend
D
D (programming language)
The D programming language is an object-oriented, imperative, multi-paradigm, system programming language created by Walter Bright of Digital Mars. It originated as a re-engineering of C++, but even though it is mainly influenced by that language, it is not a variant of C++...

 
% Dividend
Eiffel
Eiffel (programming language)
Eiffel is an ISO-standardized, object-oriented programming language designed by Bertrand Meyer and Eiffel Software. The design of the language is closely connected with the Eiffel programming method...

 
\\ Dividend
Erlang  rem Dividend
Euphoria mod Divisor
remainder Dividend
FileMaker
FileMaker
FileMaker Pro is a cross-platform relational database application from FileMaker Inc., formerly Claris, a subsidiary of Apple Inc. It integrates a database engine with a GUI-based interface, allowing users to modify the database by dragging new elements into layouts, screens, or forms...

 
Mod Divisor
Fortran
Fortran
Fortran is a general-purpose, procedural, imperative programming language that is especially suited to numeric computation and scientific computing...

mod Dividend
modulo Divisor
GML (Game Maker)
Game Maker Language
Game Maker Language is a scripting language developed for use with a computer game creation application called Game Maker. It was originally created by Mark Overmars to supplement the drag-and-drop action system used in Game Maker...

 
mod Dividend
Go
Go (programming language)
Go is a compiled, garbage-collected, concurrent programming language developed by Google Inc.The initial design of Go was started in September 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. Go was officially announced in November 2009. In May 2010, Rob Pike publicly stated that Go was being...

 
% Dividend
Haskell
Haskell (programming language)
Haskell is a standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing. It is named after logician Haskell Curry. In Haskell, "a function is a first-class citizen" of the programming language. As a functional programming language, the...

mod Divisor
rem Dividend
J
J (programming language)
The J programming language, developed in the early 1990s by Kenneth E. Iverson and Roger Hui, is a synthesis of APL and the FP and FL function-level languages created by John Backus....

 
>~ Divisor
Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

 
% Dividend
JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

 
% Dividend
Just Basic
Just BASIC
Just BASIC is a dialect of the highly popular programming language BASIC of the 1970s, for 32-bit computer systems using Windows. It's the freeware version of Liberty BASIC, popular since 1992. Just BASIC development began in 2001; first public release was in 2004...

 
MOD Dividend
Lua 5  % Divisor
Lua 4  mod(x,y) Divisor
Liberty Basic
Liberty BASIC
Liberty BASIC is a commercial computer programming language and integrated development environment . It has an interpreter developed in Smalltalk, which recognizes its own dialect of the BASIC programming language...

 
MOD Dividend
MathCad
MathCad
Mathcad is computer software primarily intended for the verification, validation, documentation and re-use of engineering calculations. First introduced in 1986 on DOS, it was the first to introduce live editing of typeset mathematical notation, combined with its automatic computations...

 
mod(x,y) Divisor
Maple (software)
Maple (software)
Maple is a general-purpose commercial computer algebra system. It was first developed in 1980 by the Symbolic Computation Group at the University of Waterloo in Waterloo, Ontario, Canada....

 
e mod m Divisor
Mathematica
Mathematica
Mathematica is a computational software program used in scientific, engineering, and mathematical fields and other areas of technical computing...

 
Mod Divisor
Microsoft Excel
Microsoft Excel
Microsoft Excel is a proprietary commercial spreadsheet application written and distributed by Microsoft for Microsoft Windows and Mac OS X. It features calculation, graphing tools, pivot tables, and a macro programming language called Visual Basic for Applications...

 
=MOD Divisor
Minitab
Minitab
Minitab is a statistics package. It was developed at the Pennsylvania State University by researchers Barbara F. Ryan, Thomas A. Ryan, Jr., and Brian L. Joiner in 1972...

 
MOD Divisor
MATLAB
MATLAB
MATLAB is a numerical computing environment and fourth-generation programming language. Developed by MathWorks, MATLAB allows matrix manipulations, plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs written in other languages,...

mod Divisor
rem Dividend
Oberon
Oberon (programming language)
Oberon is a programming language created in 1986 by Professor Niklaus Wirth and his associates at ETH Zurich in Switzerland. It was developed as part of the implementation of the Oberon operating system...

 
MOD Divisor
Objective Caml
Objective Caml
OCaml , originally known as Objective Caml, is the main implementation of the Caml programming language, created by Xavier Leroy, Jérôme Vouillon, Damien Doligez, Didier Rémy and others in 1996...

 
mod Dividend
Occam
Occam (programming language)
occam is a concurrent programming language that builds on the Communicating Sequential Processes process algebra, and shares many of its features. It is named after William of Ockham of Occam's Razor fame....

 
\ Dividend
Pascal (Delphi)
Pascal (programming language)
Pascal is an influential imperative and procedural programming language, designed in 1968/9 and published in 1970 by Niklaus Wirth as a small and efficient language intended to encourage good programming practices using structured programming and data structuring.A derivative known as Object Pascal...

 
mod Dividend
Pascal (ISO-7185 and ISO-10206)
Pascal (programming language)
Pascal is an influential imperative and procedural programming language, designed in 1968/9 and published in 1970 by Niklaus Wirth as a small and efficient language intended to encourage good programming practices using structured programming and data structuring.A derivative known as Object Pascal...

 
mod Always positive
Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...

 
% Divisor
PHP
PHP
PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...

 
% Dividend
PIC Basic Pro  \\ Dividend
PL/I
PL/I
PL/I is a procedural, imperative computer programming language designed for scientific, engineering, business and systems programming applications...

 
mod Divisor (ANSI PL/I)
PowerBuilder
PowerBuilder
PowerBuilder is an integrated development environment owned by Sybase, a division of SAP. It has been in use since 1991, peaking around 1998 with around 100,000 users....

 
mod(x,y) ?
PowerShell  % Dividend
Progress
Progress
-History:*Progress , the idea that the world can become increasingly better in terms of science, technology, modernization, liberty, democracy, quality of life, etc....

 
modulo Dividend
Prolog
Prolog
Prolog is a general purpose logic programming language associated with artificial intelligence and computational linguistics.Prolog has its roots in first-order logic, a formal logic, and unlike many other programming languages, Prolog is declarative: the program logic is expressed in terms of...

 (ISO 1995)
mod Divisor
rem Dividend
Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

 
% Divisor
RealBasic
REALbasic
Realbasic is the object-oriented dialect of the BASIC programming language used in Real Studio, a programming environment, developed and commercially marketed by Real Software, Inc of Austin, Texas for Mac OS X, Microsoft Windows, 32-bit x86 Linux and the web.- Language features :RB is a strongly...

 
MOD Dividend
R
R (programming language)
R is a programming language and software environment for statistical computing and graphics. The R language is widely used among statisticians for developing statistical software, and R is widely used for statistical software development and data analysis....

 
%% Divisor
RPG  %REM Dividend
Ruby
Ruby (programming language)
Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto...

%, modulus Divisor
remainder Dividend
Scheme modulo Divisor
remainder Dividend
Scheme R6RS mod Always positive
mod0 Closest to zero
SenseTalk
SenseTalk
SenseTalk is an English-like scripting language derived from the HyperTalk language used in HyperCard. SenseTalk was originally developed as the scripting language within the HyperSense multimedia authoring application on the NeXTStep and OpenStep platforms...

modulo Divisor
rem Dividend
Smalltalk
Smalltalk
Smalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist...

 
\\ Divisor
SQL
SQL
SQL is a programming language designed for managing data in relational database management systems ....

 (SQL:1999
SQL:1999
SQL:1999 was the fourth revision of the SQL database query language. The latest revision of the standard is SQL:2008.-Summary:The SQL:1999 standard, also known as SQL3, was published in 1999. Unlike previous editions, the standard's name used a colon instead of a hyphen for consistency with the...

)
mod(x,y) Dividend
Standard ML
Standard ML
Standard ML is a general-purpose, modular, functional programming language with compile-time type checking and type inference. It is popular among compiler writers and programming language researchers, as well as in the development of theorem provers.SML is a modern descendant of the ML...

mod Divisor
Int.rem Dividend
Stata
Stata
Stata is a general-purpose statistical software package created in 1985 by StataCorp. It is used by many businesses and academic institutions around the world...

 
mod(x,y) Always positive
Tcl
Tcl
Tcl is a scripting language created by John Ousterhout. Originally "born out of frustration", according to the author, with programmers devising their own languages intended to be embedded into applications, Tcl gained acceptance on its own...

 
% Divisor
Torque Game Engine
Torque Game Engine
The Torque Game Engine, or TGE, is a 3D computer game engine originally developed by Dynamix for the 2001 FPS Tribes 2. The Torque engine and its many derivative products are available for license from GarageGames, a company formed by many members of the Tribes 2 team at Dynamix...

 
% Dividend
Turing  mod Divisor
Verilog
Verilog
In the semiconductor and electronic design industry, Verilog is a hardware description language used to model electronic systems. Verilog HDL, not to be confused with VHDL , is most commonly used in the design, verification, and implementation of digital logic chips at the register-transfer level...

 (2001)
% Dividend
VHDL mod Divisor
rem Dividend
Visual Basic
Visual Basic
Visual Basic is the third-generation event-driven programming language and integrated development environment from Microsoft for its COM programming model...

Mod Dividend
x86 Assembly
X86 assembly language
x86 assembly language is a family of backward-compatible assembly languages, which provide some level of compatibility all the way back to the Intel 8008. x86 assembly languages are used to produce object code for the x86 class of processors, which includes Intel's Core series and AMD's Phenom and...

 
IDIV Dividend
Floating-point modulo operators in various programming languages
Language Operator Result has the same sign as
C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

 (ISO 1990)
fmod ?
C (ISO 1999)
C99
C99 is a modern dialect of the C programming language. It extends the previous version with new linguistic and library features, and helps implementations make better use of available computer hardware and compiler technology.-History:...

fmod Dividend
remainder Closest to zero
C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

 (ISO 1998)
std::fmod ?
C++ (ISO 2011) std::fmod Dividend
std::remainder Closest to zero
C#  % Dividend
Common Lisp
Common Lisp
Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in ANSI standard document ANSI INCITS 226-1994 , . From the ANSI Common Lisp standard the Common Lisp HyperSpec has been derived for use with web browsers...

mod Divisor
rem Dividend
D
D (programming language)
The D programming language is an object-oriented, imperative, multi-paradigm, system programming language created by Walter Bright of Digital Mars. It originated as a re-engineering of C++, but even though it is mainly influenced by that language, it is not a variant of C++...

 
% ?
Fortran
Fortran
Fortran is a general-purpose, procedural, imperative programming language that is especially suited to numeric computation and scientific computing...

mod Dividend
modulo Divisor
Go
Go (programming language)
Go is a compiled, garbage-collected, concurrent programming language developed by Google Inc.The initial design of Go was started in September 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. Go was officially announced in November 2009. In May 2010, Rob Pike publicly stated that Go was being...

 
math.Fmod Dividend
Haskell
Haskell (programming language)
Haskell is a standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing. It is named after logician Haskell Curry. In Haskell, "a function is a first-class citizen" of the programming language. As a functional programming language, the...

 (GHC)
Data.Fixed.mod' Divisor
Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

 
% Dividend
JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

 
% Dividend
Objective Caml
Objective Caml
OCaml , originally known as Objective Caml, is the main implementation of the Caml programming language, created by Xavier Leroy, Jérôme Vouillon, Damien Doligez, Didier Rémy and others in 1996...

 
mod_float Dividend
Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...

 
POSIX::fmod Dividend
PHP
PHP
PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...

 
fmod Dividend
Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

% Divisor
math.fmod Dividend
Ruby
Ruby (programming language)
Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto...

%, modulus Divisor
remainder Dividend
Scheme R6RS flmod Always positive
flmod0 Closest to zero
Standard ML
Standard ML
Standard ML is a general-purpose, modular, functional programming language with compile-time type checking and type inference. It is popular among compiler writers and programming language researchers, as well as in the development of theorem provers.SML is a modern descendant of the ML...

 
Real.rem Dividend

There are various ways of defining a remainder, and computers and calculators have various ways of storing and representing numbers, so what exactly constitutes the result of a modulo operation depends on the programming language
Programming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....

 and/or the underlying hardware
Computer hardware
Personal computer hardware are component devices which are typically installed into or peripheral to a computer case to create a personal computer upon which system software is installed including a firmware interface such as a BIOS and an operating system which supports application software that...

.

In nearly all computing systems, the quotient
Quotient
In mathematics, a quotient is the result of division. For example, when dividing 6 by 3, the quotient is 2, while 6 is called the dividend, and 3 the divisor. The quotient further is expressed as the number of times the divisor divides into the dividend e.g. The quotient of 6 and 2 is also 3.A...

  and the remainder satisfy


This means, that if the remainder is nonzero, there are two possible choices for the remainder, one negative and the other positive, and there are also two possible choices for the quotient. Usually, in number theory, the positive remainder is always chosen, but programming languages choose depending on the language and the signs of a and n. However, Pascal and Algol68 give a positive remainder (or 0) even for negative divisors, and some programming languages, such as C89, don't even define a result if either of n or a is negative. See the table for details. a modulo 0 is undefined in the majority of systems, although some do define it to be a.

Many implementations use truncated division where the quotient is defined by truncation
Truncation
In mathematics and computer science, truncation is the term for limiting the number of digits right of the decimal point, by discarding the least significant ones.For example, consider the real numbersThe result would be:- Truncation and floor function :...

 q = trunc(a/n), in other words it is the first integer in the direction of 0 from the exact rational quotient, and the remainder by r=an q. Informally speaking the quotient is "rounded towards zero", and the remainder therefore has the same sign as the dividend.

Knuth
Donald Knuth
Donald Ervin Knuth is a computer scientist and Professor Emeritus at Stanford University.He is the author of the seminal multi-volume work The Art of Computer Programming. Knuth has been called the "father" of the analysis of algorithms...

 described floored division where the quotient is defined by the floor function
Floor function
In mathematics and computer science, the floor and ceiling functions map a real number to the largest previous or the smallest following integer, respectively...

 q=floor(a/n) and the remainder r is
Here the quotient is always rounded downwards (even if it is already negative) and the remainder has the same sign as the divisor.

Raymond T. Boute introduces the Euclidean definition, which is the one in which the remainder is always positive or 0, and is therefore consistent with the division algorithm
Division algorithm
In mathematics, and more particularly in arithmetic, the usual process of division of integers producing a quotient and a remainder can be specified precisely by a theorem stating that these exist uniquely with given properties. An integer division algorithm is any effective method for producing...

. This definition is marked as "Always positive" in the table. Let q be the integer quotient of a and n, then:


Two corollaries are that

or, equivalently,


As described by Leijen,
Boute argues that Euclidean division is superior to the other ones in terms of regularity and useful mathematical properties, although floored division, promoted by Knuth, is also a good definition. Despite its widespread use, truncated division is shown to be inferior to the other definitions.


Common Lisp also defines round- and ceiling-division where the quotient is given by , .
IEEE 754 defines a remainder function where the quotient is rounded according to the round to nearest convention.

Common pitfalls

When the result of a modulo operation has the sign of the dividend, it can sometimes lead to surprising mistakes:

For example, to test whether an integer is odd, one might be inclined to test whether the remainder by 2 is equal to 1:


bool is_odd(int n) {
return n % 2 1;
}


But in a language where modulo has the sign of the dividend, that is incorrect, because when n (the dividend) is negative and odd, n % 2 returns -1, and the function returns false.

One correct alternative is to test that it is not 0 (because remainder 0 is the same regardless of the signs):


bool is_odd(int n) {
return n % 2 != 0;
}

Modulo operation expression
Some calculators have a mod function button, and many programming languages have a mod function or similar, expressed as mod(a, n), for example. Some also support expressions that use "%", "mod", or "Mod" as a modulo or remainder operator
Operator (programming)
Programming languages typically support a set of operators: operations which differ from the language's functions in calling syntax and/or argument passing mode. Common examples that differ by syntax are mathematical arithmetic operations, e.g...

, such as
a % n


or
a mod n


or equivalent, for environments lacking a mod function
a - (n * int(a/n)).


In most cases means modulo function and not remainder function. For example
a mod n = n * floor(a/n);
16 mod 7 = 7 * floor(16/7) = 7 * floor(2.285714286) = 7 * 0.285714286 = 2;
this is because (16 mod 7) = 16 - 7 * 2 = 2.

Performance issues
Modulo operations might be implemented such that a division with a remainder is calculated each time. For special cases, there are faster alternatives on some hardware. For example, the modulo of powers of 2 can alternatively be expressed as a bitwise AND
Bitwise operation
A bitwise operation operates on one or more bit patterns or binary numerals at the level of their individual bits. This is used directly at the digital hardware level as well as in microcode, machine code and certain kinds of high level languages...

 operation:
x % 2n x & (2n - 1).


Examples (assuming x is a positive integer):
x % 2

x & 1

x % 4 x & 3
x % 8 x & 7.


In devices and software that implement bitwise operations more efficiently than modulo, these alternative forms can result in faster calculations.

Optimizing
Compiler optimization
Compiler optimization is the process of tuning the output of a compiler to minimize or maximize some attributes of an executable computer program. The most common requirement is to minimize the time taken to execute a program; a less common one is to minimize the amount of memory occupied...

 C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

 compilers generally recognize expressions of the form expression % constant where constant is a power of two and automatically implement them as expression & (constant-1). This can allow the programmer to write clearer code without compromising performance. (Note: This will not work for the languages whose modulo have the sign of the dividend (including C), because if the dividend is negative, the modulo will be negative; however, expression & (constant-1) will always produce a positive result. So special treatment has to be made when the dividend is negative.)

In some compilers, the modulo operation is implemented as mod(a, n) = a - n * floor(a / n). For example,
mod(7, 3) = 7 - 3 * floor(7 / 3) = 7 - 3 * floor(2.33) = 7 - 3 * 2 = 7 - 6 = 1.
See also
  • Modulo
    Modulo
    In the mathematical community, the word modulo is often used informally. Generally, to say "A is the same as B modulo C" means, more-or-less, "A and B are the same except for differences accounted for or explained by C"....

     and modulo (jargon)
    Modulo (jargon)
    The word modulo is the Latin ablative of modulus which itself means "a small measure."It was introduced into mathematics in the book Disquisitiones Arithmeticae by Carl Friedrich Gauss in 1801...

     – many uses of the word "modulo", all of which grew out of Carl F. Gauss's introduction of modular arithmetic
    Modular arithmetic
    In mathematics, modular arithmetic is a system of arithmetic for integers, where numbers "wrap around" after they reach a certain value—the modulus....

    in 1801.
The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK