BAEL-3116: Finding the Least Common Multiple in Java

- Add tutorial to implement algorithms used for computing
  LCM of two or more numbers.
- List of Algorithms covered:
  - Simple Method
  - Prime Factorization Method
  - Euclidean Algorithm
  - BigInteger Class for large numbers
  - Lambda Implementation for LCM of more than two numbers
- Reference: BAEL-3116
This commit is contained in:
Tapan Avasthi
2019-07-30 16:03:25 +05:30
parent 181943a6f8
commit 04672018c5
8 changed files with 203 additions and 0 deletions

View File

@@ -0,0 +1,18 @@
package com.baeldung.lcm;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigInteger;
public class BigIntegerLCMUnitTest {
@Test
public void testLCM() {
BigInteger number1 = new BigInteger("12");
BigInteger number2 = new BigInteger("18");
BigInteger expectedLCM = new BigInteger("36");
Assert.assertEquals(expectedLCM, BigIntegerLCM.lcm(number1, number2));
}
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.lcm;
import org.junit.Assert;
import org.junit.Test;
public class EuclideanAlgorithmUnitTest {
@Test
public void testGCD() {
Assert.assertEquals(6, EuclideanAlgorithm.gcd(12, 18));
}
@Test
public void testLCM() {
Assert.assertEquals(36, EuclideanAlgorithm.lcm(12, 18));
}
@Test
public void testLCMForArray() {
Assert.assertEquals(15, EuclideanAlgorithm.lcmForArray(new int[]{3, 5, 15}));
}
@Test
public void testLCMByLambdaForArray() {
Assert.assertEquals(15, EuclideanAlgorithm.lcmByLambda(new int[]{3, 5, 15}));
}
}

View File

@@ -0,0 +1,30 @@
package com.baeldung.lcm;
import org.junit.Assert;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static com.baeldung.lcm.PrimeFactorizationAlgorithm.*;
public class PrimeFactorizationAlgorithmUnitTest {
@Test
public void testGetPrimeFactors() {
Map<Integer, Integer> expectedPrimeFactorsMapForTwelve = new HashMap<>();
expectedPrimeFactorsMapForTwelve.put(2, 2);
expectedPrimeFactorsMapForTwelve.put(3, 1);
Map<Integer, Integer> expectedPrimeFactorsMapForEighteen = new HashMap<>();
expectedPrimeFactorsMapForEighteen.put(2, 1);
expectedPrimeFactorsMapForEighteen.put(3, 2);
Assert.assertEquals(expectedPrimeFactorsMapForTwelve, getPrimeFactors(12));
Assert.assertEquals(expectedPrimeFactorsMapForEighteen, getPrimeFactors(18));
}
@Test
public void testLCM() {
Assert.assertEquals(36, PrimeFactorizationAlgorithm.lcm(12, 18));
}
}

View File

@@ -0,0 +1,15 @@
package com.baeldung.lcm;
import org.junit.Assert;
import org.junit.Test;
import static com.baeldung.lcm.SimpleAlgorithm.*;
public class SimpleAlgorithmUnitTest {
@Test
public void testLCM() {
Assert.assertEquals(36, lcm(12, 18));
}
}