Related
I ran it through an IDE and the remainder values came out 3, 2, 0, 1.
I understand the first remainder, but not the rest.
Also, how come the loop terminates? Isn't x always going to be greater than 0, therefore continuing indefinitely? Thank you.
int x = 1023;
while (x > 0)
{
printf("%d", x% 10);
x = x /10;
}
Note that in C, when both operands of a division have integer type, the division also has an integer type, and the value is the result of division rounded toward zero.
So in the first iteration, the statement x = x /10; changes x from 1023 to 102 (not 102.3).
since you are dividing integers you are getting rounded results each time,
so each iteration of x becomes
102
10
1
Just print x each time and you will see.
So 102 modulo 10 is 2
10 modul0 10 is 0
1 modulo 10 is 1
I am having an issue with the % operator in C. I know that the % operator gives the remainder of a division. However when faced with a question like 1 % 2 or 3 % 2, I get confused. After googling this, I found different solutions.
Some say that as 1 / 2 is 0.5, we round it down to 0. So 1 % 2 is 0.
Others say that as 1 / 2 is 0.5, we instead round it up, like we would in maths, to 1. So 1 % 2 is 1.
And therefore, I am now confused. My question is: What is 1 % 2?
Thank you in advance :):)
% is the remainder operator:
The % operator computes the remainder after dividing its first operand
by its second.
It's what left from the division. For example:
5 % 3 is 2.
5 % 4 is 1.
5 % 2 is 1. (Because 2 can fit 2 times in 5, 1 will be left)
When you do 1 % 2 the result is 1 because 1/2 is 0, and the remainder is.. 1.
Simply put, both are wrong methods. As you said % finds the remainder of division.
Therefore 1/2 is equal to 0 remainder 1.
And the answer is thus 1.
Also, to experiment yourself, you could have used this program:
#include <stdio.h>
main()
{
int remainder;
remainder = 1 % 2;
printf("1 %% 2 is %d", remainder);
return(0);
}
Hope this helps :)
The easy way to think of M % D (if both M and D are positive) is:
While ( M >= D){
M = M-D;
}
return M;
There is no rounding, the decimal part is simply truncated.
So, 1 / 2 is 0 and 1 % 2 is 1.
Here you need the mathematical definition on remainder.
Given two integer numbers m, d, we say that r is the remainder of the division of m and d if r satisfies two conditions:
There exists another integer k such that m == k * d + r , and
0 <= r < d.
In C we have m % d == r and m / d == k, just by following the definition above.
As you can see, there is no trucation at all (I mean: the "truncation" is consequence of the definition).
From the definition, it can be obtainded that 3 % 2 == 1 and 3 / 2 == 1.
Other examples:
4 / 3 == 1 and 5 / 3 == 1, in despite of 5.0/3.0 == 1.6666 (which
would round to 2.0).
4 % 3 == 1 and 5 % 3 == 2.
You can trust also in the formula r = m - k * d, which in C is written as:
m % d == m - (m / d) * d
However, in the standard C, the integer division follows the rule: round to 0.
Thus, with negative operands C offer different results that the mathematical ones.
We would have:
(-4) / 3 == -1, (-4) % 3 == -1 (in C), but in plain maths: (-4) / 3 = -2, (-4) % 3 = 2.
In plain maths, the remainder is always nonnegative, and less than the abs(d).
In standard C, the remainder always has the sign of the first operator.
Remark: This description (in the negative case) is for standard C99/C11 only. You must be carefull with your compiler version, and to do some tests.
In this case, what does the percentage refers to?
int myInt = 27 % 10;
myInt = 7;
What does the % mean in this code?
% means remainder, when 27 is divided by 10 leaves a remainder 7
EDIT:
My 2 cents about all the discussion about difference between modulo & remainder
Take a % b
1. When both +ve, Modulo & Remainder are one and the same
2. When a is -ve, they are not the same
For example;
a = -10, b = 3
Remainder of -10 % 3 = -1
for Modulo, add a greater multiple of 3 to your 'a' and calculate the remainder.
-10 + 12 = 2
2 % 3 = 2 is your answer
the % is modulus operator, not percentage. For percentage, you just do regular math. 50% is to multiply by .5... etc.
For future reference, the objective c mathematical operations are documented many places, including here.
Note the % is called "Modulo" operator.
% is a operator to find the remainder of a division.
The "%" in this code is called the modulus operator. This causes the processor to perform a division operation, and it returns the remainder of the division.
For example:
8 % 10 = 8
5 % 4 = 1
My friend said that there are differences between "mod" and "remainder".
If so, what are those differences in C and C++? Does '%' mean either "mod" or "rem" in C?
There is a difference between modulus (Euclidean division) and remainder (C's % operator). For example:
-21 mod 4 is 3 because -21 + 4 x 6 is 3.
But -21 divided by 4 with truncation towards 0 (as C's / operator)
gives -5 with a remainder (C -21 % 4) of -1.
For positive values, there is no difference between Euclidean and truncating division.
See https://en.wikipedia.org/wiki/Euclidean_division#Other_intervals_for_the_remainder - C's choice of truncating the remainder towards 0 (required since C99) forces a negative remainder range for negative quotients. Even in C89, when Euclidean division was allowed by the standard for /
If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.
(-21/4) * 4 + (-21%4) == -21; C99 and later require (-5) * 4 + (-1), not Euclidean -6 and 3.
Does '%' mean either "mod" or "rem" in C?
In C, % is the remainder1.
..., the result of the / operator is the algebraic quotient with any fractional part discarded ... (This is often called "truncation toward zero".) C11dr §6.5.5 6
The operands of the % operator shall have integer type. C11dr §6.5.5 2
The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder ... C11dr §6.5.5 5
What's the difference between “mod” and “remainder”?
C does not define a "mod" nor "modulo" operator/function, such as the integer modulus function used in Euclidean division or other modulo.
C defines remainder.
Let us compare "remainder" per the % operator to the Euclidean "mod".
"Euclidean mod" differs from C's a%b operation when a is negative.
// a % b, the remainder after an integer division that truncates toward 0.
7 % 3 --> 1
7 % -3 --> 1
-7 % 3 --> -1
-7 % -3 --> -1
"Mod" or modulo as in Euclidean division. The result is always 0 or positive.
7 modulo 3 --> 1
7 modulo -3 --> 1
-7 modulo 3 --> 2
-7 modulo -3 --> 2
Candidate modulo code:
int modulo_Euclidean(int a, int b) {
int m = a % b;
if (m < 0) {
// m += (b < 0) ? -b : b; // avoid this form: it is UB when b == INT_MIN
m = (b < 0) ? m - b : m + b;
}
return m;
}
Note about floating point: double fmod(double x, double y), even though called "fmod", it is not the same as Euclidean division "mod", but similar to C integer remainder:
The fmod functions compute the floating-point remainder of x/y. C11dr §7.12.10.1 2
fmod( 7, 3) --> 1.0
fmod( 7, -3) --> 1.0
fmod(-7, 3) --> -1.0
fmod(-7, -3) --> -1.0
Disambiguation: C also has a similar named function double modf(double value, double *iptr) which breaks the argument value into integral and fractional parts, each of which has the same type and sign as the argument. This has little to do with the "mod" discussion here except name similarity.
[Edit Dec 2020]
For those who want proper functionality in all cases, an improved modulo_Euclidean() that 1) detects mod(x,0) and 2) a good and no UB result with modulo_Euclidean2(INT_MIN, -1). Inspired by 4 different implementations of modulo with fully defined behavior.
int modulo_Euclidean2(int a, int b) {
if (b == 0) TBD_Code(); // perhaps return -1 to indicate failure?
if (b == -1) return 0; // This test needed to prevent UB of `INT_MIN % -1`.
int m = a % b;
if (m < 0) {
// m += (b < 0) ? -b : b; // avoid this form: it is UB when b == INT_MIN
m = (b < 0) ? m - b : m + b;
}
return m;
}
1 Prior to C99, C's definition of % was still the remainder from division, yet then / allowed negative quotients to round down rather than "truncation toward zero". See Why do you get different values for integer division in C89?. Thus with some pre-C99 compilation, % code can act just like the Euclidean division "mod". The above modulo_Euclidean() will work with this alternate old-school remainder too.
sign of remainder will be same as the divisible and the sign of modulus will be same as divisor.
Remainder is simply the remaining part after the arithmetic division between two integer number whereas Modulus is the sum of remainder and divisor when they are oppositely signed and remaining part after the arithmetic division when remainder and divisor both are of same sign.
Example of Remainder:
10 % 3 = 1 [here divisible is 10 which is positively signed so the result will also be positively signed]
-10 % 3 = -1 [here divisible is -10 which is negatively signed so the result will also be negatively signed]
10 % -3 = 1 [here divisible is 10 which is positively signed so the result will also be positively signed]
-10 % -3 = -1 [here divisible is -10 which is negatively signed so the result will also be negatively signed]
Example of Modulus:
5 % 3 = 2 [here divisible is 5 which is positively signed so the remainder will also be positively signed and the divisor is also positively signed. As both remainder and divisor are of same sign the result will be same as remainder]
-5 % 3 = 1 [here divisible is -5 which is negatively signed so the remainder will also be negatively signed and the divisor is positively signed. As both remainder and divisor are of opposite sign the result will be sum of remainder and divisor -2 + 3 = 1]
5 % -3 = -1 [here divisible is 5 which is positively signed so the remainder will also be positively signed and the divisor is negatively signed. As both remainder and divisor are of opposite sign the result will be sum of remainder and divisor 2 + -3 = -1]
-5 % -3 = -2 [here divisible is -5 which is negatively signed so the remainder will also be negatively signed and the divisor is also negatively signed. As both remainder and divisor are of same sign the result will be same as remainder]
I hope this will clearly distinguish between remainder and modulus.
In C and C++ and many languages, % is the remainder NOT the modulus operator.
For example in the operation -21 / 4 the integer part is -5 and the decimal part is -.25. The remainder is the fractional part times the divisor, so our remainder is -1. JavaScript uses the remainder operator and confirms this
console.log(-21 % 4 == -1);
The modulus operator is like you had a "clock". Imagine a circle with the values 0, 1, 2, and 3 at the 12 o'clock, 3 o'clock, 6 o'clock, and 9 o'clock positions respectively. Stepping quotient times around the clock clock-wise lands us on the result of our modulus operation, or, in our example with a negative quotient, counter-clockwise, yielding 3.
Note: Modulus is always the same sign as the divisor and remainder the same sign as the quotient. Adding the divisor and the remainder when at least one is negative yields the modulus.
Modulus, in modular arithmetic as you're referring, is the value left over or remaining value after arithmetic division. This is commonly known as remainder. % is formally the remainder operator in C / C++. Example:
7 % 3 = 1 // dividend % divisor = remainder
What's left for discussion is how to treat negative inputs to this % operation. Modern C and C++ produce a signed remainder value for this operation where the sign of the result always matches the dividend input without regard to the sign of the divisor input.
% is a remainder(leftover after dividend / divisor) NOT modulus.
You could write your own modulus function using the remainder(%) by the relation
((n%m)+m)%m
where `n` is the given number and `m` is the modulus
Find below the difference between the remainder and modulus values for the range n = (-7,7) and m = 3
n -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7
-------------------------------------------------------------------------
%(-m) -1 0 -2 -1 0 -2 -1 0 1 2 0 1 2 0 1 => remainder
% m -1 0 -2 -1 0 -2 -1 0 1 2 0 1 2 0 1 => remainder
mod m 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 => ((n%m)+m)%m
mod(-m) -1 0 -2 -1 0 -2 -1 0 -2 -1 0 -2 -1 0 -2 => ((n%m)+m)%m
Tips to remember:
n%(-m) = +(remainder)
(-n)%(m) = -(remainder)
sign of 'm' doesn't matter
n mod (-m) = -(result)
(-n) mod m = +(result)
sign of 'n' doesn't matter
For +ve 'n' and '%(-m)' or '%m' or 'mod m' gives the same remainder
In mathematics the result of the modulo operation is the remainder of the Euclidean division. However, other conventions are possible. Computers and calculators have various ways of storing and representing numbers; thus their definition of the modulo operation depends on the programming language and/or the underlying hardware.
7 modulo 3 --> 1
7 modulo -3 --> -2
-7 modulo 3 --> 2
-7 modulo -3 --> -1
Dynamic integer will be any number from 0 to 150.
i.e. - number returns 41, need to return 50. If number is 10 need to return 10. Number is 1 need to return 10.
Was thinking I could use the ceiling function if I modify the integer as a decimal...? then use ceiling function, and put back to decimal?
Only thing is would also have to know if the number is 1, 2 or 3 digits (i.e. - 7 vs 94 vs 136)
Is there a better way to achieve this?
Thank You,
n + (10 - n % 10)
How this works. The % operator evaluates to the remainder of the division (so 41 % 10 evaluates to 1, while 45 % 10 evaluates to 5). Subtracting that from 10 evaluates to how much how much you need to reach the next multiple.
The only issue is that this will turn 40 into 50. If you don't want that, you would need to add a check to make sure it's not already a multiple of 10.
if (n % 10)
n = n + (10 - n % 10);
You can do this by performing integer division by 10 rounding up, and then multiplying the result by 10.
To divide A by B rounding up, add B - 1 to A and then divide it by B using "ordinary" integer division
Q = (A + B - 1) / B
So, for your specific problem the while thing together will look as follows
A = (A + 9) / 10 * 10
This will "snap" A to the next greater multiple of 10.
The need for the division and for the alignment comes up so often that normally in my programs I'd have macros for dividing [unsigned] integers with rounding up
#define UDIV_UP(a, b) (((a) + (b) - 1) / (b))
and for aligning an integer to the next boundary
#define ALIGN_UP(a, b) (UDIV_UP(a, b) * (b))
which would make the above look as
A = ALIGN_UP(A, 10);
P.S. I don't know whether you need this extended to negative numbers. If you do, care should be taken to do it properly, depending on what you need as the result.
What about ((n + 9) / 10) * 10 ?
Yields 0 => 0, 1 => 10, 8 => 10, 29 => 30, 30 => 30, 31 => 40
tl;dr: ((n + 9) / 10) * 10 compiles to the nicest (fastest) asm code in more cases, and is easy to read and understand for people that know what integer division does in C. It's a fairly common idiom.
I haven't investigated what the best option is for something that needs to work with negative n, since you might want to round away from zero, instead of still towards +Infinity, depending on the application.
Looking at the C operations used by the different suggestions, the most light-weight is Mark Dickinson's (in comments):
(n+9) - ((n+9)%10)
It looks more efficient than the straightforward divide / multiply suggested by a couple people (including #bta): ((n + 9) / 10) * 10, because it just has an add instead of a multiply. (n+9 is a common subexpression that only has to be computed once.)
It turns out that both compile to literally identical code, using the compiler trick of converting division by a constant into a multiply and shift, see this Q&A for how it works. Unlike a hardware div instruction that costs the same whether you use the quotient, remainder, or both results, the mul/shift method takes extra steps to get the remainder. So the compiler see that it can get the same result from a cheaper calculation, and ends up compiling both functions to the same code.
This is true on x86, ppc, and ARM, and all the other architectures I've looked at on the Godbolt compiler explorer. In the first version of this answer, I saw an sdiv for the %10 on Godbolt's gcc4.8 for ARM64, but it's no longer installed (perhaps because it was misconfigured?) ARM64 gcc5.4 doesn't do that.
Godbolt has MSVC (CL) installed now, and some of these functions compile differently, but I haven't taken the time to see which compile better.
Note that in the gcc output for x86, multiply by 10 is done cheaply with lea eax, [rdx + rdx*4] to do n*5, then add eax,eax to double that. imul eax, edx, 10 would have 1 cycle higher latency on Intel Haswell, but be shorter (one less uop). gcc / clang don't use it even with -Os -mtune=haswell :/
The accepted answer (n + 10 - n % 10) is even cheaper to compute: n+10 can happen in parallel with n%10, so the dependency chain is one step shorter. It compiles to one fewer instruction.
However, it gives the wrong answer for multiples of 10: e.g. 10 -> 20. The suggested fix uses an if(n%10) to decide whether to do anything. This compiles into a cmov, so it's longer and worse than #Bta's code. If you're going to use a conditional, do it to get sane results for negative inputs.
Here's how all the suggested answers behave, including for negative inputs:
./a.out | awk -v fmt='\t%4s' '{ for(i=1;i<=NF;i++){ a[i]=a[i] sprintf(fmt, $i); } } END { for (i in a) print a[i]; }'
i -22 -21 -20 -19 -18 -12 -11 -10 -9 -8 -2 -1 0 1 2 8 9 10 11 12 18 19 20 21 22
mark -10 -10 -10 -10 0 0 0 0 0 0 0 0 0 10 10 10 10 10 20 20 20 20 20 30 30
igna -10 -10 -10 0 0 0 0 0 10 10 10 10 10 10 10 10 10 20 20 20 20 20 30 30 30
utaal -20 -20 -20 -10 -10 -10 -10 -10 0 0 0 0 0 10 10 10 10 10 20 20 20 20 20 30 30
bta -10 -10 -10 -10 0 0 0 0 0 10 10 10 10 10 10 10 10 10 20 20 20 20 20 30 30
klatchko -10 -10 -10 -10 0 0 0 0 0 0 0 0 0 10 10 10 10 10 20 20 20 20 20 30 30
branch -10 -10 -20 0 0 0 0 -10 10 10 10 10 0 10 10 10 10 10 20 20 20 20 20 30 30
(transpose awk program)
Ignacio's n + (((9 - (n % 10)) + 1) % 10) works "correctly" for negative integers, rounding towards +Infinity, but is much more expensive to compute. It requires two modulo operations, so it's essentially twice as expensive. It compiles to about twice as many x86 instructions, doing about twice the work of the other expressions.
Result-printing program (same as the godbolt links above)
#include <stdio.h>
#include <stdlib.h>
int f_mark(int n) { return (n+9) - ((n+9)%10); } // good
int f_bta(int n) { return ((n + 9) / 10) * 10; } // compiles to literally identical code
int f_klatchko(int n) { return n + 10 - n % 10; } // wrong, needs a branch to avoid changing multiples of 10
int f_ignacio(int n) { return n + (((9 - (n % 10)) + 1) % 10); } // slow, but works for negative
int roundup10_utaal(int n) { return ((n - 1) / 10 + 1) * 10; }
int f_branch(int n) { if (n % 10) n += (10 - n % 10); return n; } // gcc uses cmov after f_accepted code
int main(int argc, char**argv)
{
puts("i\tmark\tigna\tutaal\tbta\tklatch\tbranch");
for (int i=-25 ; i<25 ; i++)
if (abs(i%10) <= 2 || 10 - abs(i%10) <= 2) // only sample near interesting points
printf("%d\t%d\t%d\t%d\t%d\t%d\t%d\n", i, f_mark(i), f_accepted(i),
f_ignacio(i), roundup10_utaal(i), f_bta(i), f_branch(i));
}
How about using integer math:
N=41
N+=9 // Add 9 first to ensure rounding.
N/=10 // Drops the ones place
N*=10 // Puts the ones place back with a zero
in C, one-liner:
int inline roundup10(int n) {
return ((n - 1) / 10 + 1) * 10;
}
Be aware that answers based on the div and mod operators ("/" and "%") will not work for negative numbers without an if-test, because C and C++ implement those operators incorrectly for negative numbers. (-3 mod 5) is 2, but C and C++ calculate (-3 % 5) as -3.
You can define your own div and mod functions. For example,
int mod(int x, int y) {
// Assert y > 0
int ret = x % y;
if(ret < 0) {
ret += y;
}
return ret;
}
n + (((9 - (n % 10)) + 1) % 10)
You could do the number mod 10. Then take that result subtract it from ten. Then add that result to the original.
if N%10 != 0 #added to account for multiples of ten
a=N%10
N+=10-a
int n,res;
...
res = n%10 ? n+10-(n%10) : n;
or
res = (n / 10)*10 + ((n % 10) ? 10:0);
In pseudo code:
number = number / 10
number = ceil(number)
number = number * 10
In Python:
import math
def my_func(x):
return math.ceil(x / 10) * 10
That should do it. Keep in mind that the above code will cast an integer to a float/double for the arithmetic, and it can be changed back to an integer for the final return. Here's an example with explicit typecasting
In Python (with typecasting):
import math
def my_func(x):
return int(math.ceil(float(x) / 10) * 10)
round_up(int i)
{
while(i%10) {
i++;
}
return(i);
}