0

the question is simple:

Line up every number from 1 to 1000 who are not divisions of 3 or 5 and multiply them together. e.g 1 - 10 would be "1 * 2 * 4 * 7 * 8" = 448

My code looks like this:

    ArrayList<Integer> list = new ArrayList();

    for(int i = 1; i <= 1000; i++)
    {
        list.add(i);
    }

    for(int k = 0; k < list.size(); k++)
    {
        if(list.get(k) % 3 == 0 || list.get(k) % 5 == 0)
        {
            list.remove(k);
        }
    }

    int answer = 1;

    for(int x = 0; x < list.size(); x++)
    {
        answer *= list.get(x);
    }

    System.out.println(answer);

The first two for/loops works well but at the third something clearly goes wrong as answer keeps getting returned at a 0 value, which doesn't make sense since answer is not 0 and no value in list is 0.

Any thoughts?

Hummus
  • 21
  • 2
  • I'm not sure about the zero result, but I think your list.remove call might cause an interesting issue - when you call remove, I believe all the following values shift over a place - so if you remove value at 6, the value at index 7 moves to 6, 8 to 7, and so on - which would result in your code "skipping" the value after the one you remove. – romeara Sep 04 '15 at 13:27
  • I decided to skim through the arraylist to see if 0 ever occured but as I was doing it, it occured to me just how massively big this number would be so I tried changing the variable answer to a double and it now said 'infinity' so I guess when I used int and it returned 0 I suppose it just gave up. – Hummus Sep 04 '15 at 13:48
  • hmm the number is getting out of range – Ankit Chaudhary Sep 04 '15 at 13:49

0 Answers0