integer arithmetic

 

intro

a normal CPU's integer arithmetic instructions act differently than unlike what you were taught in math class.

integer divide

12/5=2, not 2.4, and 1/3=0. if you want to know what the integer equivelant result is, get out your calculator, do the calculation & ignore the decimal point and everything after it, and that's your number.

because computer integer arithmetic acts this way, we have a problem called aliasing, where the order of what you do first makes a difference in the result you get. for example 12/5*3=2*3=6 as opposed to 3*12/5=36/5=7. the computer can only do 2 numbers at a time and 1 operator (+,×,/,−)

one trick in integerizing divisions, is to set the order of multiplies and divides so that you get required results like no-zeros-preferred for instance.
for example 12/5*3=2*3=6 as opposed to 3*12/5=36/5=7 and 3*5/12=1 as opposed to 5/12*3=0*3=0: rearranging equations so that numbers/vars you know will be larger become the numerator and numbers/vars you know will be smaller become the denominator ensures you get a non-zero result. rearranging the mutiplies makes a slight difference too. I had to do this a few times in assembler and other languages. But it doesn't make a lot of difference - you're only going to be off by 1. it depends on whether that's important to you or not.


integer remainder (modulus, or C's % operator)

mod or modulus (%) is simply the remainder of an integer divide. integer computer arithmetic is a little strange. it's not like normal math divides where you get a real number result. integer modulus works like this:

assign = lhs % rhs;
assign gets the remainder of lhs / rhs, where the divided amount is thrown away and the number that is left over from the divide is what is returned.
for instance, 6%3=0, 5%3=2, 4%3=1, 3%3=0, 2%3=2, 1%3=1, 0%3=0.
4%2=0, 3%2=1, 2%2=0, 1%2=1, 0%2=0.
if you mod something by 2, it alternates between 2 values, 0..1.
if you mod it by 3, it alternates between 3 values, 0..2.
and so on.