I am trying to get the smallest positive number that is evenly divisible by all of the numbers from 1 to 20. But somehow I am stuck in the end of the program. My answer is coming 40 which is wrong. Here is my code:
public class Lessons {
public static void main(String[] args) {
int n;
int s = 0;
for (n = 21; n > 0; n++)
{
for (int m = 1; m <= 20; m++)
{
s = n % m;
}
if (s == 0)
{
System.out.println(n);
break;
}
}
}
}
Any helps???
You're effectively only ever checking whether n%20 == 0
. This loop:
for (int m = 1; m <= 20; m++) {
s = n % m;
}
does run for m from 1 to 20, but you always overwrite s
and never do anything with the value before resetting it the next time through the loop. You need to check the result of n % m
for each iteration of the loop, perhaps like:
for (n = 21; n > 0; n++) {
bool divisibleByAll = true;
for (int m = 1; m <= 20; m++) {
s = n % m;
if(s != 0) {
divisibleByAll = false;
break; //don't bother checking the rest
}
}
if (divisibleByAll) {
System.out.println(n);
break;
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments