Interview Questions

Test divisors of three
The question is as follows:
You will be given 2 parameters: a low and high number. Your goal is to print all numbers between low and high, and for each of these numbers print whether or not the number is divisible by 3. If the number is divisible by 3, print the word "div3" directly after the number.

## Example

If the function call is: test_divisors(2, 10) then the output should be: 2 3 "div3" 4 5 6 "div3" 7 8 9 "div3" 10

## Solution

We'll solve this problem by first creating a loop that will print each number from low to high. Once we have the code for that written, we'll add a conditional that will check if the number is evenly divisible by 3 by using the mod operator.

## Code

```function test_divisors(low, high) {

// we'll store all numbers and strings within an array
// instead of printing directly to the console
var output = [];

for (var i = low; i <= high; i++) {

// simply store the current number in the output array
output.push(i);

// check if the current number is evenly divisible by 3
if (i % 3 === 0) { output.push('div3'); }

}

// return all numbers and strings
return output;

}

test_divisors(2, 10);
```
```def test_divisors(low, high):

# we'll store all numbers and strings within an array
# instead of printing directly to the console
output = []

for i in range(low, high+1):

# simply store the current number in the output array
output.append(i)

# check if the current number is evenly divisible by 3
if i % 3 == 0:
output.append('div3')

# return all numbers and strings
return output

print test_divisors(2, 10)
```
mrdaniel published this on 12/14/15 |