Recently got a response from a recruiter which included a coding assignment. The assignment is similar to FizzBuzz and is trivial :
Optimized Math
This program should be a short piece of code that prints all of the positive integers from 1 to 100 as described more fully below. The program may contain multiple methods, and if using an OO language, should be contained within a single class or object. The program should be designed so that it begins execution when invoked through whichever mechanism is most common for the implementation language.
Print out all positive integers from 1 to 100, inclusive and in order.
Print messages to standard output, matching the Sample Output below.
In the output, state whether the each integer is ‘odd’ or ‘even’ in the output.
If the number is divisible by three, instead of stating that the number is odd or even, state that the number is ‘divisible by three’.
If the number is divisible by both two and three, instead of saying that the number is odd, even or divisible by three; state that the number is ‘divisible by two and three’.
Design the logic of the loop to be as efficient as possible, using the minimal number of operations to perform the required logic.
Sample Output
The number ‘1’ is odd.
The number ‘2’ is even.
The number ‘3’ is divisible by three.
…
The number ‘6’ is divisible by two and three
I completed the program easily but I just wanted a couple more sets of eyes to look at what I did before I submit it.
Here is my solution:
// Iterates from 1-100
for(var i = 1; i <= 100; i++) {
// Checks if number is divisible by two and three
if(i % 2 == 0 && i % 3 == 0) {
console.log('The number ' + i + ' is divisible by two and three');
}
// Checks if number is divisible by 3, but not 2
else if(i % 3 == 0) {
console.log('The number ' + i + ' is divisible by three');
}
// Checks if number is odd, but not divisible by 2 or 3
else if(i % 2 != 0) {
console.log('The number ' + i + ' is odd');
}
// Checks if number is even
else {
console.log('The number ' + i + ' is even');
}
}
I know this is a basic problem, but am I overlooking anything? The question mentions efficiency, should I being using a different approach like .map
?