checknmate's blog

By checknmate, history, 3 days ago, In English

Can anybody help why using the expression :

  • int x = ((2*b-c)%a) + ((2*b-c) < a) give different answer as compared to :

  • int x = ((2*b-c)%a!=0) + ((2*b-c) < a)

Problem reference : 1624B - Make AP

What I am trying is that x will be 0 if the 2*b-c is divisible by a and second condition is fulfilled (2*b-c < a) but the solution is accepted when I write a boolean expression and not when I directly use modulo value

  • Vote: I like it
  • +1
  • Vote: I do not like it

»
3 days ago, # |
  Vote: I like it +9 Vote: I do not like it

A very good question indeed.

The problem with this approach is that p%q can sometimes give negative outputs { just try (-1)%2 }.

In some cases in your solution {(2*b-c)%a)} is negative and {(2*b-c) < a} is positive with same magnitude cancelling out each other giving x=0 which would have have been 1+1=2 when using this {((2*b-c)%a!=0) + ((2*b-c) < a)}.

  • »
    »
    3 days ago, # ^ |
      Vote: I like it +9 Vote: I do not like it

    You can still make the first method work:

    If p is negative p%q will lie between -q and 0 no matter how large p is in magnitude, so to get positive result we use ((p%q)+q)%q which will lie between 0 and +q.

    So try this:

    ((2*b-c)%a)+a)%a

    ((a+c)%(2*b))+2*b)%(2*b)

    ((2*b-a)%c)+c)%c

    It will get accepted

    • »
      »
      »
      3 days ago, # ^ |
        Vote: I like it +8 Vote: I do not like it

      That was quite a good point I was missing. Thank you!

      • »
        »
        »
        »
        3 days ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        No Problem, happy to help