The challenge

Count the number of divisors of a positive integer n.

Random tests go up to n = 500000.

Examples

1
2
3
4
numberOfDivisors(4)  == 3 // 1, 2, 4
numberOfDivisors(5)  == 2 // 1, 5
numberOfDivisors(12) == 6 // 1, 2, 3, 4, 6, 12
numberOfDivisors(30) == 8 // 1, 2, 3, 5, 6, 10, 15, 30

The solution in Java code

Option 1:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public class FindDivisor {

  public long numberOfDivisors(int n) {
      long counter = 0;
      for(int i=1; i<=n; i++){
          if(n % i == 0){
          counter++;
          }
      }
      return counter;
  }
}

Option 2:

1
2
3
4
5
6
import java.util.stream.IntStream;
public class FindDivisor {
  public long numberOfDivisors(int n) {
    return IntStream.range(1, n+1).filter(i -> n%i==0).count();
  }
}

Option 3:

1
2
3
4
5
6
7
8
9
import java.util.stream.*;

public class FindDivisor {

  public long numberOfDivisors(int n) {
      return IntStream.rangeClosed(1, n).filter(x -> n % x == 0).count();
  }

}

Test cases to validate our solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import static org.junit.Assert.assertEquals;
import org.junit.Test;

public class DividerTests {

  FindDivisor fd = new FindDivisor();

	@Test
	public void fourTest() {
		assertEquals("Sould return 3 if the parameter equals 4", 3, fd.numberOfDivisors(4));
	}
  
	@Test
	public void fiveTest() {
		assertEquals("Sould return 2 if the parameter equals 5", 2, fd.numberOfDivisors(5));
	}
  
	@Test
	public void twelveTest() {
		assertEquals("Sould return 6 if the parameter equals 12", 6, fd.numberOfDivisors(12));
	}
  
	@Test
	public void thirtyTest() {
		assertEquals("Sould return 8 if the parameter equals 30", 8, fd.numberOfDivisors(30));
	}
}