Modulo that 'wraps' the number?

Steven Schveighoffer schveiguy at gmail.com
Mon Jan 21 15:01:27 UTC 2019


On 1/21/19 2:33 AM, Paul Backus wrote:
> On Monday, 21 January 2019 at 04:52:53 UTC, NaN wrote:
>> On Sunday, 20 January 2019 at 18:51:54 UTC, Steven Schveighoffer wrote:
>>> On 1/20/19 1:28 PM, faissaloo wrote:
>>>> In Python -1%3 == 2 however in D -1%3 == -1
>>>> Is there a standard library function or something that gives me the 
>>>> Python version of modulo?
>>>
>>> Hm... (n%3+3)%3 should work.
>>>
>>> -Steve
>>
>> You only need the
>>
>> (n % 3) + 3
> 
> You need both:
> 
> (-3 % 3) + 3 == 3
> ((-3 % 3) + 3) % 3 == 0

Probably, this optimizes into better code, but maybe the optimizer 
already does this with the expression above:

auto tmp = n % 3;
if(tmp < 0)
    tmp += 3;

It's just not a nice single expression.

-Steve


More information about the Digitalmars-d-learn mailing list