모든 챌린지
보통 0명 해결 정답률 0%

Prime Factorization

Break a number into its prime factors, listed from smallest to largest with repetition.

배우게 될 내용

  • Divide out each factor as many times as it occurs
  • Stop trial division once d × d exceeds what is left
  • Recognise that a leftover above 1 is a prime factor

문제

번역본 보기

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

예시

예시 1
입력:
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].

예시 2
입력:
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

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에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

코더마다 가장 좋은 통과 풀이입니다. 더 빠르고, 메모리를 덜 쓰고, 평가가 좋은 풀이가 위에 옵니다.

아직 통과한 풀이가 없습니다. 풀어서 1위를 차지하세요.

다른 사람의 풀이 보기

커뮤니티 솔루션

아직 공개된 풀이가 없습니다. 문제를 풀고 첫 풀이를 공유하세요.