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.The problem with my code is, it keeps giving the answer 466
. 466 is the wrong answer to this problem, so I'm wondering what I did wrong.
Here is my code.
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
}
}
You are calculating the number of multiples. Not their sum. The totalNumber++ is going to be incremented whenever a number is a multiple of 3 or 5, but the 'multiple' is not stored.
Change totalNumber++
to totalNumber += number
and your problem is solved.
package sumofmultiples;
public class sumofMultiples{
public static void main(String[] args){
int number = 1; //<- the number that we are checking to be multiple.
int totalNumber= 0; //<- Total number of multiples counted so far.
while (number < 1000){
if ((number % 3) == 0 || (number % 5) == 0){
totalNumber += number;
}
number++; //<- Move on to the next number.
}
System.out.println(totalNumber); //<- Print results
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.