問題
Every integer greater than 1 can be written as a product of primes in exactly one way, apart from the order of the factors (the fundamental theorem of arithmetic). For example, 360 = 2 × 2 × 2 × 3 × 3 × 5. Finding that list is called prime factorization.
Implement prime_factorization(n).
n can be as large as 10^12, so the classic approach is trial division: divide out 2 as long as you can, then 3, and so on. You only need to try divisors d while d × d ≤ the part of n that is still left; whatever remains above 1 at the end is itself prime. That keeps the work to about √n ≈ 10^6 steps even when n is a large prime or the product of two large primes.
Input
n: The number to factor.
Output
Return the prime factors of n in ascending order, repeating each prime as many times as it divides n, so that the product of the list is n. For n = 1 return an empty list. If n is prime, the list has the single element n.
制約
1 ≤ n ≤ 10^12
例
入力:
n = 360
期待される出力:
expected = [2, 2, 2, 3, 3, 5]
入力:
long long n = 360;
期待される出力:
std::vector<long long> expected = {2, 2, 2, 3, 3, 5};
入力:
long n = 360;
期待される出力:
long[] expected = new long[] {2, 2, 2, 3, 3, 5};
解説
360 = 2 × 180 = 2 × 2 × 90 = 2 × 2 × 2 × 45 = 2 × 2 × 2 × 3 × 15 = 2 × 2 × 2 × 3 × 3 × 5, so the answer is [2, 2, 2, 3, 3, 5].
入力:
n = 97
期待される出力:
expected = [97]
入力:
long long n = 97;
期待される出力:
std::vector<long long> expected = {97};
入力:
long n = 97;
期待される出力:
long[] expected = new long[] {97};
解説
No prime up to √97 ≈ 9.8 (2, 3, 5, 7) divides 97, so it is prime and the answer is [97].
解き方のヒント
まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。
ヒント 1
Divide by 2 while you can, then move to 3, 5, 7, and so on.
ヒント 2
Shrink n each time you find a factor, and compare d × d with the shrunken n.
ヒント 3
If something greater than 1 is left after the loop, it is the largest prime factor.
目安の計算量
O(√n) time, O(log n) extra space for the result
参考資料
この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。