Add all the natural numbers below one thousand that are multiples of 3 or 5.

We are starting with ProjectEuler Problems from today. We would show the most basic code that would solve the problem. Hints would be provided to solve the problem in an efficient manner.

Here is the Problem 1 of ProjectEuler Problems. This is the most simple problem of all.

The logic of the problem solving is adding all multiples of 3 and add all multiples of 5. Now that the total sum would contain numbers that are multiple of 3 and 5 added two times, we would need to substract sum of numbers that are multiple of 3 and 5.


Java implementation of above is as follows:


/*PROBLEM: Add all the natural numbers below
one thousand that are multiples of 3 or 5.*/
//LOGIC: S = S(3)+s(5)-S(3&5)
//OUTPUT: The sum is: 234168.
class A{
int sum,num=1;
void calSum(){
while(++num<1000){
//System.out.println("Num ="+num);
if(num%3==0) sum += num;
if(num%5==0) sum += num;
if(num%3==0 && num%5==0) sum -= num;
//System.out.println("The sum is: "+sum);
}
System.out.println("The sum is: "+sum);
}
}
public class Test1{
public static void main(String [] args){
A a = new A();
a.calSum();
}
}

More problems from ProjectEulers coming, so continue solving and checking buttur.com for any getting one probable way of solving the problem.

Leave a Reply

Your email address will not be published. Required fields are marked *