How the% operator works in this solution for Project Euler # 1

I recently started learning python and this was my original solution for Euler # 1:

n = 0
for i in xrange(1000):
    if i % 3 == 0 or i % 5 == 0:
        n += i
print n

      

I found this online:

n = 0
for i in xrange(1000):
    if not i % 3 or not i % 5:
        n += i
print n

      

Both give the correct answer (233168).

I really don't understand how the "not x% y" part evaluates to True / False when iterating over the range. Can someone please clarify this?

+3


source to share


2 answers


The result x % y

will be True if it is non-zero, thus the following condition:

if not i % 3

      

equal if i % 3 == 0

.

For a better understanding, see the following bool table:



 i % 3    | not i % 3      | i % 3 == 0

  True    |     False      |  True==0(false)-> False
  False   |     True       |  False==0(false)->True 

      

Which shows that (not i % 3) is equal with (i % 3 == 0)

.

Note that True and False in a table is only from the point of view if

, not its result!

+2


source


%

is a modular operator. In this example

if i % 3 == 0 or i % 5 == 0:

This is true if it is i

evenly divisible by 3 or 5.



The% (modulo) operator gives the remainder of the first argument divided by the second. Numeric arguments are first converted to a generic type. The zero right argument throws a ZeroDivisionError. The arguments can be floating point numbers, for example 3.14% 0.7 equals 0.34 (since 3.14 equals 4 * 0.7 + 0.34.) The modulo operator always produces a result with the same sign as and its second operand (or zero); the absolute value of the result is strictly less than the absolute value of the second operand [2].

https://docs.python.org/2/reference/expressions.html

+1


source







All Articles