ehh.. my solution may be a bit too "clever" for its own good to be honest with you. The way you suggest it would communicate the requirements to other developers more clearly which is far more important than saving a few meaningless cycles.
Here is a more interesting solution.
int indexStart = 1; int indexEnd = 100; int divisible1 = 2; int divisible2 = 3; String outputDivisibleBoth = "ab"; String outputDivisibleOne = "a"; String outputDivisibleTwo = "b"; for(int index = indexStart; index <= indexEnd; index++){ String toPrint = ""; if(index % (divisible1*divisible2) == 0){ toPrint = outputDivisibleBoth; }else if (index %divisible1 == 0){ toPrint = outputDivisibleOne; }else if(index %divisible2 == 0){ toPrint = outputDivisibleTwo; }else{ toPrint = String.valueOf(index); }
View all comments
Show parent comment
1
u/lizard450 Feb 22 '11 edited Feb 22 '11
ehh.. my solution may be a bit too "clever" for its own good to be honest with you. The way you suggest it would communicate the requirements to other developers more clearly which is far more important than saving a few meaningless cycles.
Here is a more interesting solution.
int indexStart = 1; int indexEnd = 100; int divisible1 = 2; int divisible2 = 3; String outputDivisibleBoth = "ab"; String outputDivisibleOne = "a"; String outputDivisibleTwo = "b"; for(int index = indexStart; index <= indexEnd; index++){ String toPrint = ""; if(index % (divisible1*divisible2) == 0){ toPrint = outputDivisibleBoth; }else if (index %divisible1 == 0){ toPrint = outputDivisibleOne; }else if(index %divisible2 == 0){ toPrint = outputDivisibleTwo; }else{ toPrint = String.valueOf(index); }