samedi 25 juillet 2015

Why does this not work when trying to find the sum of all multiples of 3 and 5 in 1000?

There are a lot of questions on here about the project euler question about finding the sum of all the multiples of 3 and 5 below 1000, but I am a beginner at java, and I attempted to make my own program to try and figure this out. There are several answers on proper codes on how to figure this out, but I am trying to get the answer myself, not by copy pasting someone else's work. The problem with what I made is that it keeps giving the answer 466. 466 is the wrong answer to this problem, so I'm wondering what I did wrong. Here is what I made.

package sumofmultiples;

public class sumofMultiples{
    public static void main(String[] args){
        int number = 1; //<- This is the number that we are checking to be a multiple.
        int totalNumber= 0; //<- Total number of multiples counted so far.
        while (number < 1000){
            if ((number % 3) == 0){
                totalNumber++;
                //The number is a multiple of 3.
            } else if ((number % 5) == 0){
                totalNumber++;
                //The number is a multiple of 5
            }
            number++; //<- Move on to the next number.
        }
        System.out.println(totalNumber); //<- Print results
    }
}

Aucun commentaire:

Enregistrer un commentaire