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);
}
}
CodePudding user response:
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.
CodePudding user response:
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
.
CodePudding user response:
Certainly your issue is with the if
condition. It should be n >= 1000
Also you can simplify your algo like this. An alternative solution to your question.
public class Main {
public static void main(String[] args) {
System.out.println(sum(1000, 3, 5));
}
private static int sum(int i, int a, int b) {
i = --i;
int c = a * b;
int k1 = i / a;
int k2 = i / b;
int k3 = i / c;
return (k1 * (a (k1 * a)))/2 (k2 * (b (k2 * b)))/2 - (k3 * (c (k3 * c)))/2;
}
}
Note this only works if a
and b
are prime numbers. If a
and b
are not prime, then c
should be LCM
of a
and b
int c = lcm(a,b)