Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find the sum of the multiples of 3 and 5 below 1000

Tags:

java

Ok guys, so I'm doing the Project Euler challenges and I can't believe I'm stuck on the first challenge. I really can't see why I'm getting the wrong answer despite my code looking functional:

import java.util.ArrayList;


public class Multithree {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        ArrayList<Integer> x = new ArrayList<Integer>();
        ArrayList<Integer> y = new ArrayList<Integer>();
        int totalforthree = 0;
        int totalforfive = 0;

        int total =0;

        for(int temp =0; temp < 1000 ; temp++){
            if(temp % 3 == 0){
                x.add(temp);
                totalforthree += temp;
            }
        }

        for(int temp =0; temp < 1000 ; temp++){
            if(temp % 5 == 0){
                y.add(temp);
                totalforfive += temp;
            }
        }

        total = totalforfive + totalforthree;



        System.out.println("The multiples of 3 or 5 up to 1000 are: " +total);

    }

}

I'm getting the answer as 266333 and it says it's wrong...

like image 828
Tloz Avatar asked Oct 30 '13 19:10

Tloz


People also ask

How do you find the sum of multiples of 3 and 5?

We can find the sum of multiples of 3 and 5 separately. At this point, if we add both, we get a number which has the multiples of 15 (3 * 5) added twice. To get our ultimate answer, we need to subtract multiples of 15 from the sum. This is simple as we can use our insights to get the sum of multiples of 15.

How do you find the multiples of 3 below 1000?

multiple of 3: 3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60,63,66,69,72,75,78,81,84,87,90,93,96,99. multiple of 4: 4,8,12,16,20,24,28,32,36,40,44,48,52,56,60,64,68,72,76,80,84,88,92,96. therefore, first three common multiples between 3 and 4 12,24,36.

What are multiples of 3 and 5?

The multiples of 3 are: 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, … The multiples of 5 are: 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, … The common multiples of 3 and 5 are: 15, 30, …

What is the sum of all multiples of 3 between 1 and 1000?

Therefore the sum of all multiples of 3 between 1 and 1000 is 166833.


1 Answers

you should use the same for loop for both to aviod double counting numbers that are multiple of both. such as 15,30...

   for(int temp =0; temp < 1000 ; temp++){
        if(temp % 3 == 0){
            x.add(temp);
            totalforthree += temp;
        }else if(temp % 5 == 0){
            y.add(temp);
            totalforfive += temp;
        }
    }
like image 164
Todoy Avatar answered Sep 22 '22 22:09

Todoy