codewars070 Sum by Factors 經過因子求和

Instructions 題目說明

題目說明的連接java

解體要點

  • 求一個整數的質因子
  • 利用TreeMap的自動排序功能

測試樣例

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();
	}
}
相關文章
相關標籤/搜索