Since developing a love for programming, I have always tried to solve any problem on my own. In this pursuit, I have solved several problems, including those from Project Euler some books and from the preparation stages for the Informatics Olympiad. I have tried to include all the problems that I have solved on my own approach up to this day.
In order to solve this problem, we are go through a little bit of mathematical intuition. Since we are called to determine the sum of all the numbers \((1, 1000)\) which are divislbe by \(3\) or \(5\), we need to list all the numbers multiple of \(3\) or \(5\). So, we need to run a loop under from \(1\) to \(1000\) exclusive. Which means we in programming, our initial value would be \(2\) and end just before \(1000\). Then initialize sum would be \(0\) and the iteration of \(i\) will be added up continuously untill \(1000\). And then we will printf the result of sum.
So, first of all, we need to initialize our sum variable as \(0\). Then we need to use a for loop untill \(1000\) from initializing i variable as \(2\) because according to the problem,
\(1\) and \(1000\) will be exclusive \((1, 1000)\). Then we will set a condition that if any \(i\) is divislbe by \(3\) or \(5\), then it will be summed up the value inside the sum variable. And then we will return sum as our answer.
#include <stdio.h>
int divisibleSum(int n);
int main(){
int n = 1000;
divisibleSum(n);
return 0;
}
int divisibleSum(int n){
int sum = 0;
for(int i = 2; i < n; i++){
if(i % 3 == 0 || i % 5 == 0){
sum += i;
}
}
printf("%d\n", sum);
return sum;
}