Count the divisors of a number in Java

The challenge

Count the number of divisors of a positive integer n.

Random tests go up to n = 500000.

Examples

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:

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:

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:

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

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));
	}
}
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments