Re: mod operator for signed integers
"Geoff" <geoff@invalid.invalid> ha scritto nel messaggio
news:vk31q617k5188j3qfsalvqj4hjnl05n57h@4ax.com...
> On Sat, 9 Apr 2011 07:53:05 -0700 (PDT), "dr.oktopus"
> <blindwilly@freeonline.zzn.com> wrote:
>
>>Ok, today I seems to be a little dumb.
>>What I have to do is to make mod operator (m % n) work even
>>if m is a negative number.
>>
>>This is what I mean:
>>
>>given n = 5
>>
>> 7 became 2
>> 6 .. 1
>> 5 .. 0
>> 4 .. 4
>> 3 .. 3
>> 2 .. 2
>> 1 .. 1
>> 0 .. 0
>>-1 .. 4
>>-2 .. 3
>>-3 .. 2
>>-4 .. 1
>>-5 .. 0
>>-6 .. 4
>>-7 .. 3
>>
>>I think that, for a operation like m % n, it could be:
>>
>>unsigned my_mod (int m, unsigned n)
>>{
>> unsigned um;
>>
>> if (m < 0) {
>> um = -m;
>> return n - um % n;
here if for example n=5 and um=10 [m==-10]
n - um % n== 5 - (10%5) == 5 but the result has to be 0..4
so it should be one test
if(result==5) result=0;
>> }
>> return m % n;
>>}
>>
>>but, if m is INT_MIN, for example, its two complement (um)
>>is 0, right? So, my_mod returns n (that is wrong).
>>
>>What's the right (and smart) way?
>
> r = m < 0 ? -m % n : m % n;
i think this
r = (m<0 ? (n-(-m%n))%n : m%n)
or better
unsigned myMod(int m, unsigned n)
{unsigned mm;
// prevent seg fault on error but wrong result
if(n==0) return -1;
if(m>=0) {mm=m; return mm%n;}
mm=-m; mm%=n;
if(mm==n) mm=0;
return mm;
}
but this is untested and i can make wrong on that
Buona giornata.
> return r;
|