題目說明的連接java
import static org.junit.Assert.*; import org.junit.*; public class SumOfDividedTest { @Test public void testOne() { int[] lst = new int[] {12, 15}; assertEquals("(2 12)(3 27)(5 15)", SumOfDivided.sumOfDivided(lst)); } }
// source: https://www.codewars.com/kata/54d496788776e49e6b00052f/train/java import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import java.util.TreeMap; public class SumOfDivided { private static List<Integer> primeFactors(int n) { List<Integer> list = new ArrayList<Integer>(); for (int i = 2; i * i <= n; i++) { if (n % i == 0) { list.add(i); while (n % i == 0) { n = n / i; } } } if (n > 1) { list.add(n); } return list; } private static int sum(int n, int[] l) { int sum = 0; for (int i : l) { if (i % n == 0) { sum += i; } } return sum; } public static String sumOfDivided(int[] l) { TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>(); for (int i = 0; i < l.length; i++) { List<Integer> list = SumOfDivided.primeFactors(l[i]); for (Integer n : list) { if (!map.containsKey(n)) { int sum = SumOfDivided.sum(n, l); map.put(n, sum); } } } StringBuilder sb = new StringBuilder(); for (Entry<Integer, Integer> item : map.entrySet()) { sb.append(String.format("(%d %d)", item.getKey(), item.getValue())); } return sb.toString(); } }