Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is modulus different in different programming languages?

Tags:

Perl

print 2 % -18; 

-->

-16 

Tcl

puts [expr {2 % -18}] 

-->

-16 

but VBScript

wscript.echo 2 mod -18 

-->

2 

Why the difference?

like image 544
bugmagnet Avatar asked Jan 16 '09 13:01

bugmagnet


People also ask

Why do we use modulus in programming?

The modulus operator is useful in a variety of circumstances. It is commonly used to take a randomly generated number and reduce that number to a random number on a smaller range, and it can also quickly tell you if one number is a factor of another.

What is modulus in programming?

The modulus operator is added in the arithmetic operators in C, and it works between two available operands. It divides the given numerator by the denominator to find a result. In simpler words, it produces a remainder for the integer division. Thus, the remainder is also always an integer number only.

What are the different modulus in Python?

The % symbol in Python is called the Modulo Operator. It returns the remainder of dividing the left hand operand by right hand operand. It's used to get the remainder of a division problem.

What is the difference between division and modulus operators in C language?

Modulo − Represents as % operator. And gives the value of the remainder of an integer division. Division − represents as / operator. And gives the value of the quotient of a division.


1 Answers

The wikipedia answer is fairly helpful here.

A short summary is that any integer can be defined as

a = qn + r

where all of these letters are integers, and

0 <= |r| < |n|.

Almost every programming language will require that (a/n) * n + (a%n) = a. So the definition of modulus will nearly always depend on the definition of integer division. There are two choices for integer division by negative numbers 2/-18 = 0 or 2/-18 = -1. Depending on which one is true for your language will usually change the % operator.

This is because 2 = (-1) * -18 + (-16) and 2 = 0 * -18 + 2.

For Perl the situation is complicated. The manual page says: "Note that when use integer is in scope, "%" gives you direct access to the modulus operator as implemented by your C compiler. This operator is not as well defined for negative operands, but it will execute faster. " So it can choose either option for Perl (like C) if use integer is in scope. If use integer is not in scope, the manual says " If $b is negative, then $a % $b is $a minus the smallest multiple of $b that is not less than $a (i.e. the result will be less than or equal to zero). "

like image 50
Nick Fortescue Avatar answered Sep 23 '22 02:09

Nick Fortescue