Generally, try to think about the problem before brute-forcing it.
Is there an easy way to sum all the multiples of 3 below \$N\$? Of course there is.
First we note that the largest multiple of 3 is \$3 * \lfloor\frac{N}{3}\rfloor\$ and the sum of all the multiples is then \$3 * 1 + 3 * 2 + ... 3 * \lfloor\frac{N}{3}\rfloor\$. Factor out the 3 and you get \$3 * (1 + 2 + 3 + ... \lfloor\frac{N}{3}\rfloor)\$. Now we use Gauss's trick for summing the natural numbers to get a nice easy formula for the sum: \$3*x*\frac{x+1}{2}\$, where \$x\$ is \$\lfloor\frac{N}{3}\rfloor\$.
Similarly, we can get the sum for the multiples of 5, and add the results together. However, we then have a bunch of duplicates (namely multiples of 15)
which we can also calculate in a similar manner and then subtract to get the final result.
This approach completely eliminates any and all looping, and so will be super quick.
Now, let's discuss your code. Here's a list of suggestions:
If you are prompting the user, provide some helpful hints as to what you are expecting as input.
Having hardcoded bounds such as yours is unintuitive. Have your sum be a long or even long long (depending on the desired platform) and you will not run into issues with integer inputs, which are guaranteed by scanf(%d)
. This will also cut down on the indentation, increasing readability.
Variable names are important. While it is pretty easy to see that i
, k
are the bounds, and j
, l
are counter variables after reading the code, it would be even easier to understand with lower_bound
, upper_bound
and i
, j
for the counters (per standard practices).
Consider generalizing the problem to create a function that will be reusable elsewhere.
3
(or5
, but let's stick with one term for the moment) there were? What stunt didGauss
do as a young student that's applicable? \$\endgroup\$