How to Count Odd Numbers Below N using Java

The challenge

Given a number n, return the number of positive odd numbers below n, EASY!

oddCount(7) //=> 3, i.e [1, 3, 5] oddCount(15) //=> 7, i.e [1, 3, 5, 7, 9, 11, 13]
Code language: Java (java)

Expect large Inputs!

Test cases

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)); } }
Code language: Java (java)

The solution in Java

At first we would approach this in a programming type of way:

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; } }
Code language: Java (java)

But for really large numbers, this solution will quickly timeout.

So we revisit it from a maths stand-point:

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 ); } }
Code language: Java (java)

Or simply:

public class OddNumbers { public static int oddCount(int n) { return n/2; } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments