Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Project Euler Problem - 1 does not return the value I expected

I did not learn loops using for yet, so I solved this problem using while but I can't find the issue with my problem, sum should be 233168 apparently, and I am getting 234168 I simply cannot identify where I missed it.

Question: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

package net.projecteuler;

public class Problem01 {
    public static void main(String[] args) {
        
        int n, sum;
        boolean notFinished = true;
        n = 0;
        sum = 0;
        
        
        while(notFinished) {
            if(n % 3 == 0 || n % 5 == 0) {
                sum = (sum + n);
            }
            n = (n + 1);
            if(n > 1000) {
                notFinished = !true;
            }
        }
        System.out.print("A soma dos números é " + sum);
    }
}
like image 788
fabinfabinfabin Avatar asked Jun 26 '26 18:06

fabinfabinfabin


2 Answers

Your condition is wrong. The problem statement is (bolding for emphasis):

Find the sum of all the multiples of 3 or 5 below 1000.

Whereas your program also sums 1000 itself, which is divisible by 5. If you change the condition n > 1000 to n >= 1000, you'll get the correct answer.

Side note: You should really look into for loops. That would be a much better fit for this challenge.

like image 189
Mureinik Avatar answered Jun 28 '26 08:06

Mureinik


Your condition is wrong. The while loop runs one too many times, because you are comparing n > 1000 instead of n >= 1000.

With that being said, you can also improve your loop. The boolean variable is not needed, as you can straight up check the condition in the while statement, like this - while (n < 1000).

In addition, if you are going to use your boolean variable, I would probably not set it to false by saying isFinished = !true, but by doing isFinished = false or isFinished = !isFinished.

like image 30
alonkh2 Avatar answered Jun 28 '26 07:06

alonkh2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!