I recently found a 'question' that requires me to find the sum of all multiples of 3 and 5 under 1000, I sadly cheated and found some code online to help build a code in python:
sum=0
for i in range(999):
if not(i %3 == 0) or not (i % 5):
sum=sum+i
print sum
However, even though it works, I feel guilty that I had to cheat to answer this question. I do not understand what the if not means, and why I cannot use the regular if statement. Can someone please clear this up for me? Thanks waco001
P.S. In other languages like C, this:
int problem1()
{
int sum=0;
for(int i=0;i<1000;i++)
{
if(i%3 == 0 || i%5 == 0)
{
sum+=i ;
}
}
return sum ;
}
Works perfectly?!?
You don't need such a brute force calculation. You can do this by hand. First, some notation. Let $$ M_3 = 3\mathbb{Z} \cap [1, 999] = \{ \text{multiples of 3 between 1 and 999, inclusive} \} $$ This definition works for any $k \in \mathbb{Z}$. The quantity that you are looking for is $$ S = \sum_{n \in M_3 \cup M_5} n $$
Which numbers are in $M_3 \cup M_5$? Multiples of $3$ or $5$, of course, but you must be careful. Multiples of $15 = 3 \cdot 5$ are multiples of both $3$ and $5$. In fact, $M_3 \cap M_5 = M_{15}$, so $$ \begin{align} S &= \sum_{n \in M_3} n + \sum_{n \in M_5} n - \sum_{n \in M_{15}} n \\ \end{align} $$ I will show you how to calculate one of these sums. (The other two are strictly analogous.) Consider $$ \sum_{n \in M_3} n = 3 + 6 + \cdots + 996 + 999 $$ How many summands are there? $\left\lfloor \frac{999}{3} \right\rfloor = \left\lfloor 333 \right\rfloor = 333$. Thus, by pairing terms à la Aryabhata (and famously young K.F. Gauss), you have $$ \sum_{n \in M_3} n = \frac{333(3 + 999)}{2} = 166\,833. $$