001 Overview
001 Overview
As you have solved this problem we do not have to explain that all numbers divisible by 3
and/or by 5 should be counted.
So the first numbers to be added would be:
3, 5, 6, 9, 10, 12, 15 and so on.
A simple way to do this is to go through all numbers from 1 to 999 and test whether they are
divisible by 3 or by 5.
This would result in code like:
target=999
sum=0
for i=1 to target do
if (i mod 3=0) or (i mod 5)=0 then sum:=sum+i
output sum
Let’s look at the details of our function and take as example n=3.
We would have to add:
3+6+9+12+......+999=3*(1+2+3+4+...+333)
For n=5 we would get:
5+10+15+...+995=5*(1+2+....+199)
Now note that 199=995/5 but also 999/5 rounded down to the nearest integer.
In many programming languages there exists a separate operator for that: div or \.
If we now also note that 1+2+3+...+p=½*p*(p+1) our program becomes:
target=999
Function SumDivisibleBy(n)
p=target div n
return n*(p*(p+1)) div 2
EndFunction
Output SumDivisibleBy(3)+SumDivisibleBy(5)-SumDivisibleBy(15)
copyright Project Euler,further distribution without the consent of the author(s) prohibited
Author: hk