Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mathematical modulus in c#

Tags:

c#

modulo

Is there a library function in c# for the mathematical modulus of a number - by this I specifically mean that a negative integer modulo a positive integer should yield a positive result.

edited to provide an example:

-5 modulo 3 should return 1

like image 902
penguat Avatar asked Apr 22 '10 13:04

penguat


People also ask

How do you calculate modulus in C?

rem = num1 % num2; We calculate the remainder using the Modulus(%) operator. printf("Remainder = %d", rem); printf("Remainder = %d", rem);

What does '%' mean in C?

% is the modulo operator. It returns the remainder of <number> / <number> . For example: 5 % 2. means 5 / 2 , which equals 2 with a remainder of 1, so, 1 is the value that is returned.

How do you write modulus in programming?

Enter the Modulo The modulo operation (abbreviated “mod”, or “%” in many programming languages) is the remainder when dividing. For example, “5 mod 3 = 2” which means 2 is the remainder when you divide 5 by 3.

Can you use C modulo?

Modulo Division operator % in C language can be used only with integer variables or constants.


2 Answers

Try (a % b) * Math.Sign(a)

Try this; it works correctly.

static int MathMod(int a, int b) {     return (Math.Abs(a * b) + a) % b; } 
like image 95
SLaks Avatar answered Sep 19 '22 21:09

SLaks


x < 0 ? ((x % m) + m) % m : x % m; 
like image 27
Michael Petito Avatar answered Sep 20 '22 21:09

Michael Petito