The challenge
Given a number n, return the number of positive odd numbers below n, EASY!
1
2
|
oddCount(7) //=> 3, i.e [1, 3, 5]
oddCount(15) //=> 7, i.e [1, 3, 5, 7, 9, 11, 13]
|
Expect large Inputs!
Test cases
1
2
3
4
5
6
7
8
9
10
11
|
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
public class SolutionTest {
@Test
public void fixedTests() {
assertEquals(7, OddNumbers.oddCount(15));
assertEquals(7511, OddNumbers.oddCount(15023));
}
}
|
The solution in Java
At first we would approach this in a programming type of way:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public class OddNumbers {
public static int oddCount(int n){
// create a variable to hold out count
int count = 0;
// loop from 1 to the value of `n`
for(int i=1; i<n; i++) {
// increment count if i divided by 2 has a remainder
if (i%2!=0) count++;
}
// return out count
return count;
}
}
|
But for really large numbers, this solution will quickly timeout.
So we revisit it from a maths stand-point:
1
2
3
4
5
6
7
8
9
10
|
import java.lang.*;
public class OddNumbers {
public static int oddCount(int n) {
// divide the number by 2 and return an integer of that
return (int) Math.floor( n/2 );
}
}
|
Or simply:
1
2
3
4
5
6
7
|
public class OddNumbers {
public static int oddCount(int n) {
return n/2;
}
}
|