Find Numbers which are Divisible by given Number in Java

1 min read 245 words

The challenge

Complete the function which takes two arguments and returns all numbers which are divisible by the given divisor. First argument is an array of numbers and the second is the divisor.

Example

divisibleBy([1, 2, 3, 4, 5, 6], 2) == [2, 4, 6]

The solution in Java

Option 1 (using streams):

import java.util.stream.*;
import java.util.Arrays;

public class EvenNumbers {
  public static int[] divisibleBy(int[] numbers, int divider) {
  
    return Arrays.stream(numbers)
                 .filter(i -> (i % divider) == 0)
                 .toArray();
  }
}

Option 2 (writing the code ourselves):

public class EvenNumbers {
    public static int[] divisibleBy(int[] numbers, int divider) {
        int count = 0;
        for (int number : numbers){
          if (number % divider == 0){
            count ++;
          }
        }
        int[] arr = new int[count];
        int i = 0;        
        for (int number : numbers){
          if (number % divider == 0){
            arr[i] = number;
            i++;
          }        
        }
        return arr;
    }
}

Test cases to validate our code

import java.util.Arrays;
import java.util.Random;
import static org.junit.Assert.assertArrayEquals;
import org.junit.Test;

public class EvenNumbersTest {
  private static int[] divisibleBy(int[] numbers, int divider) {
    return Arrays.stream(numbers).filter(n -> n % divider == 0).toArray();
  }
  
  @Test public void testSimple() {
    assertArrayEquals(new int[] {2,4,6}, EvenNumbers.divisibleBy(new int[] {1,2,3,4,5,6},2));
    assertArrayEquals(new int[] {3,6}, EvenNumbers.divisibleBy(new int[] {1,2,3,4,5,6},3));
    assertArrayEquals(new int[] {0,4}, EvenNumbers.divisibleBy(new int[] {0,1,2,3,4,5,6},4));
  }
  
  @Test public void testRandom() {
    Random r = new Random();
    for (int i = 0; i < 20; i++) {
      int n = 2 + r.nextInt(10);
      int[] a = r.ints(100,0,100).toArray();
      assertArrayEquals(divisibleBy(a, n), EvenNumbers.divisibleBy(a, n));
    }
  }
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags