Determine if N Is Divisible by X and Y in Java


The challenge

Create a function that checks if a number n is divisible by two numbers x AND y. All inputs are positive, non-zero digits.

Examples

1) n =   3, x = 1, y = 3 =>  true because   3 is divisible by 1 and 3
2) n =  12, x = 2, y = 6 =>  true because  12 is divisible by 2 and 6
3) n = 100, x = 5, y = 3 => false because 100 is not divisible by 3
4) n =  12, x = 7, y = 5 => false because  12 is neither divisible by 7 nor 5

The solution in Java code

Option 1:

public class DivisibleNb {
  public static Boolean isDivisible(long n, long x, long y) {
      return (n%x ==0) && (n%y ==0);
  }
}

Option 2:

import java.util.Arrays;

public class DivisibleNb {
  public static Boolean isDivisible(long n, long x, long y) {
    return Arrays.asList(x, y).stream().allMatch(i -> n % i == 0);
  }
}

Test cases to validate our solution

import static org.junit.Assert.*;

import java.util.Random;

import org.junit.Test;

public class DivisibleNbTests {

  @Test
  public void test1() {
    assertEquals(true, DivisibleNb.isDivisible(12,4,3));
  }
  @Test
  public void test2() {
    assertEquals(false, DivisibleNb.isDivisible(3,3,4));
  }
  @Test
  public void test3() {
    assertEquals(false, DivisibleNb.isDivisible(8,3,4));
  }
  @Test
  public void test4() {
    assertEquals(true, DivisibleNb.isDivisible(48,3,4));
  }
  @Test
  public void test5() {
    assertEquals(true, DivisibleNb.isDivisible(100,5,10));
  }
  @Test
  public void test6() {
    assertEquals(false, DivisibleNb.isDivisible(100,5,3));
  } 
  @Test
  public void test7() {
    assertEquals(true, DivisibleNb.isDivisible(4,4,2));
  } 
  @Test
  public void test8() {
    assertEquals(false, DivisibleNb.isDivisible(5,2,3));
  } 
  @Test
  public void test9() {
    assertEquals(true, DivisibleNb.isDivisible(1000000,1000000,1000000));
  } 
  @Test
  public void test10() {
    assertEquals(false, DivisibleNb.isDivisible(1,1000000,1000000));
  } 
  @Test
  public void test11() {
    Random rnd = new Random();
    for (int i = 0; i < 50; i++) {      
      long r = rnd.nextLong();
            long n = 100000 * r;
            long k = 100 * r + rnd.nextInt(2);
            long l = 10 * r;
            System.out.println("Divisible n : " + n + " ? by : " + k + " and : " + l);
            assertEquals((n%k == 0) && (n%l == 0), DivisibleNb.isDivisible(n, k, l));
    }
  } 
    
    
}