This is my first question on StackOverflow so please pardon any mistakes but let me know about them. I am trying to do problem 5 on Project Euler in Java. I feel like my code is correct but I can not get the answer.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
public class Main {
public static void main(String[] args) {
boolean a = true;
int counter = 0;
int b = 1;
while (a) {
for (int i = 1; i <= 20; i ) {
if (b % i == 0) {
counter ;
}
if (counter == 20) {
System.out.println(b);
a = false;
}
else {
b ;
}
counter = 0;
}
}
}
}
CodePudding user response:
The problem is that your nesting is wrong.
Within the for (int i = 1; i <= 20; i )
loop you increment counter
if b
is divisible by i
.
The you do some checks and in the end set counter
to zero again.
That means that your counter
only ever reaches a maximum value of 1 (if b
is divisible by a specific i
).
You probably meant to write
for (int i = 1; i <= 20; i ) {
if (b % i == 0) {
counter ;
}
}
if (counter == 20) {
System.out.println(b);
a = false;
}
else {
b ;
}
counter = 0;
which will give the correct result - although the algorithm is still terribly slow.