This method finds the smallest positive number that is evenly divisible by all numbers from 1 to 20.
I am wondering if there is a better way to test if all iterations of a for
loop completed successfully. When I put the found boolean outside the for
loop, it was terminating my while
loop prematurely since the break in the for
loop goes to the end and executes whatever is below the for
loop inside the while
loop. It also seems a bit sloppy to subtract the number that is given and then add 1 to it inside the while
loop. But if I put the number++ below the for
loop after found is set true and I don't need to increment the number anymore. It increments one last time.
For example, for the number 20, the answer is 232792560. But due to the last increment it would return 232792561, which is an incorrect answer.
public int getLowestDiv(int n) {
//initialize found variable, as we havent found the number yet
boolean found = false;
/* initilize the number as what was passed to this method minus 1, since we will increment below*/
int number = n - 1;
while (found != true) {
number++;
for (int i = 1; i <= n; i++) {
//for 1 to int that was passed divide the current number and see if its divisible
if (number % i != 0) {
break;
} else if (i == n)
found = true;
}
}
return number;
}
I have looked through the specs for Java's loops and didn't find anything about handling these type of situations. Specifically, I will loop for a certain number of iterations, testing if something is true, and if not, break, but only execute a particular statement if the for
loop passed the condition on all iterations. I would like to see what the status-quo is when it comes to this as I've run into it before.