List all factors of a number in Java (#12646)
* List all factors of a number in Java * format the map code in the test
This commit is contained in:
parent
46499a2419
commit
0ea458117e
@ -0,0 +1,39 @@
|
||||
package com.baeldung.factors;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class FactorsOfInteger {
|
||||
public static Set<Integer> getAllFactorsVer1(int n) {
|
||||
Set<Integer> factors = new HashSet<>();
|
||||
for (int i = 1; i <= n; i++) {
|
||||
if (n % i == 0) {
|
||||
factors.add(i);
|
||||
}
|
||||
}
|
||||
return factors;
|
||||
}
|
||||
|
||||
public static Set<Integer> getAllFactorsVer2(int n) {
|
||||
Set<Integer> factors = new HashSet<>();
|
||||
for (int i = 1; i <= Math.sqrt(n); i++) {
|
||||
if (n % i == 0) {
|
||||
factors.add(i);
|
||||
factors.add(n / i);
|
||||
}
|
||||
}
|
||||
return factors;
|
||||
}
|
||||
|
||||
public static Set<Integer> getAllFactorsVer3(int n) {
|
||||
Set<Integer> factors = new HashSet<>();
|
||||
int step = n % 2 == 0 ? 1 : 2;
|
||||
for (int i = 1; i <= Math.sqrt(n); i += step) {
|
||||
if (n % i == 0) {
|
||||
factors.add(i);
|
||||
factors.add(n / i);
|
||||
}
|
||||
}
|
||||
return factors;
|
||||
}
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
package com.baeldung.factors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
|
||||
class FactorsOfIntegerUnitTest {
|
||||
//@formatter:off
|
||||
private final static Map<Integer, Set<Integer>> FACTOR_MAP = ImmutableMap.of(
|
||||
0, ImmutableSet.of(),
|
||||
1, ImmutableSet.of(1),
|
||||
20, ImmutableSet.of(1, 2, 4, 5, 10, 20),
|
||||
24, ImmutableSet.of(1, 2, 3, 4, 6, 8, 12, 24),
|
||||
97, ImmutableSet.of(1, 97),
|
||||
99, ImmutableSet.of(1, 3, 9, 11, 33, 99),
|
||||
100, ImmutableSet.of(1, 2, 4, 5, 10, 20, 25, 50, 100)
|
||||
);
|
||||
//@formatter:on
|
||||
|
||||
@Test
|
||||
void givenAnInteger_whenCallingFindAllFactorsTheDraftVersion_shouldGetExpectedResult() {
|
||||
FACTOR_MAP.forEach((number, expected) -> assertEquals(expected, FactorsOfInteger.getAllFactorsVer1(number)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenAnInteger_whenCallingFindAllFactorsVer2_shouldGetExpectedResult() {
|
||||
FACTOR_MAP.forEach((number, expected) -> assertEquals(expected, FactorsOfInteger.getAllFactorsVer2(number)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenAnInteger_whenCallingFindAllFactorsVer3_shouldGetExpectedResult() {
|
||||
FACTOR_MAP.forEach((number, expected) -> assertEquals(expected, FactorsOfInteger.getAllFactorsVer3(number)));
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user