Prime Factorisation of a Number

99
0

Given an array queries of n positive integers, return the prime factorisation of each number. Keep the results in the same order as the queries and list each number’s prime factors in ascending order, including repeats.

For example, 12 = 2 × 2 × 3, so its factorisation is [2, 2, 3]. The number 1 has no prime factors, so its list is empty.

Example 1

Input: queries = [2, 3, 4, 5, 6]
Output: [[2], [3], [2, 2], [5], [2, 3]]
Explanation: The numbers 2, 3, and 5 are already prime. The other two factor as 4 = 2 × 2 and 6 = 2 × 3.

Example 2

Input: queries = [7, 12, 18]
Output: [[7], [2, 2, 3], [2, 3, 3]]
Explanation: The number 7 is prime. Dividing 12 by 2 twice leaves 3, while dividing 18 by 2 leaves 9 = 3 × 3.

Brute Force Approach

For each query, find its prime factors by repeatedly dividing the number. Whenever a divisor divides it exactly, record that divisor and divide it out. Repeat with the same divisor to include every occurrence. For example, dividing 12 by 2 twice records [2, 2] and leaves 3.

First, remove all factors of 2. The remaining number is then odd, so we can skip even divisors and try only 3, 5, 7, and so on.

We only need to test divisors up to the square root of the remaining number, which gets smaller as we divide. Any composite remainder must have a factor at or below its square root. If a value greater than 1 remains after this check, it must be prime, so append it to the factors.

Approach

  1. Initialise an empty result list to store the factors for all queries.

  2. For each query, create an empty list of factors.

  3. While the number is divisible by 2, record 2 and divide the number by 2.

  4. Try odd divisors starting from 3 while divisor <= number / divisor. This checks the square-root limit without multiplying.

  5. For each divisor, keep recording it and dividing the number until it no longer divides exactly.

  6. Append the remaining number if it is greater than 1.

  7. Add the factor list to the result. The factors are already in ascending order.

  8. Return the result after processing all queries.

Dry Run

Prime factorization of a number Brute force

Prime factorization of a number Brute force

Solution

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> primeTillN(int n) {
// There are no prime numbers smaller than 2.
if (n < 2) {
return {};
}
// Initially, assume every number from 0 to n is prime.
vector<bool> isPrime(n + 1, true);
// 0 and 1 are not prime numbers.
isPrime[0] = false;
isPrime[1] = false;
// Stores all prime numbers found.
vector<int> primes;
// Check every number from 2 to n.
for (long long p = 2; p <= n; ++p) {
// If p was already marked, it is not prime.
if (!isPrime[p]) {
continue;
}
// p is prime, so add it to the answer.
primes.push_back(p);
// Mark all multiples of p as non-prime.
// Start from p * p because smaller multiples
// have already been marked by smaller primes.
for (long long multiple = p * p;
multiple <= n;
multiple += p) {
isPrime[multiple] = false;
}
}
// Return all prime numbers in increasing order.
return primes;
}
};
int main() {
Solution solution;
int n = 7;
// Find all prime numbers from 2 to n.
vector<int> primes = solution.primeTillN(n);
// Print the prime numbers.
for (int prime : primes) {
cout << prime << ' ';
}
cout << '\n';
return 0;
}

Complexity Analysis

Let U be the largest query value and F be the total number of factors returned, including repeats.

Time Complexity : O(N × √U) in the worst case. A prime near U can require testing odd divisors up to its square root.

Space Complexity : O(1) auxiliary space. The returned lists take O(N + F) space.

Optimal Approach

When there are many queries, we can prepare the smallest prime factor of every number up to the largest query value. Store these factors in an array called spf, so spf[x] gives the smallest prime that divides x.

Build this table once using Sieve of Eratosthenes. Visit candidates in increasing order. If a number has no recorded factor, it is prime. Set its smallest prime factor to itself, then mark its multiples. Fill only entries that are still 0, so a smaller factor already recorded is preserved. Start marking from p × p because smaller multiples already have a smaller prime factor.

Once the table is ready, factorising a query takes one lookup and one division per factor. For example, spf[12] = 2, so record 2 and divide 12 by 2 to get 6. Repeat for 6 and then 3 to obtain [2, 2, 3].

Approach

  1. Find the largest query value U and initialise an spf array of size U + 1 with zeros.

  2. Visit each candidate p from 2 through U.

  3. If spf[p] is 0, then p is prime. Set spf[p] = p.

  4. Mark the multiples of p starting from p × p. Set spf[multiple] = p only if that entry is still 0.

  5. For each query, create an empty factor list.

  6. Repeatedly append spf[number] and divide number by that factor until it reaches 1.

  7. Add the factor list to the result. The factors appear in ascending order, including repeated factors.

  8. Return the result after processing all queries.

Dry Run

Prime Factorisation of a Number

Prime Factorisation of a Number

Solution

#include <bits/stdc++.h>
using namespace std;
class Solution {
private:
// Build an array where spf[x] stores the smallest prime factor of x.
vector<int> buildSmallestPrimeFactors(int limit) {
// Initially, SPF is 0 for every number.
vector<int> spf(limit + 1LL, 0);
// Process every number from 2 to limit.
for (long long p = 2; p <= limit; ++p) {
// If SPF is already assigned, p is composite.
if (spf[p] != 0) {
continue;
}
// No smaller prime divides p, so p is prime.
// A prime number is its own smallest prime factor.
spf[p] = p;
// Mark the smallest prime factor of multiples of p.
// Start from p * p because smaller multiples
// have already been processed by smaller primes.
for (long long multiple = p * p;
multiple <= limit;
multiple += p) {
// Assign only if no smaller prime factor
// has already been assigned.
if (spf[multiple] == 0) {
spf[multiple] = p;
}
}
}
return spf;
}
public:
// Find prime factors for every number in the query array.
vector<vector<int>> primeFactors(const vector<int>& queries) {
// Handle an empty query array.
if (queries.empty()) {
return {};
}
// Find the maximum number among all queries.
// We only need to build the SPF array up to this limit.
int limit = *max_element(queries.begin(), queries.end());
// Create one answer vector for each query.
vector<vector<int>> result(queries.size());
// Numbers smaller than 2 have no prime factors.
if (limit < 2) {
return result;
}
// Build the smallest prime factor array once.
vector<int> spf = buildSmallestPrimeFactors(limit);
// Process every query using the precomputed SPF array.
for (size_t i = 0; i < queries.size(); ++i) {
int number = queries[i];
// Repeatedly divide the number by its smallest
// prime factor until the number becomes 1.
while (number > 1) {
// Get the smallest prime factor of the current number.
int factor = spf[number];
// Store this prime factor.
result[i].push_back(factor);
// Remove one occurrence of this prime factor.
number /= factor;
}
}
return result;
}
};
int main() {
vector<int> queries = {7, 12, 18};
Solution solution;
// Calculate the prime factorization of all queries.
vector<vector<int>> result = solution.primeFactors(queries);
// Print each number followed by its prime factors.
for (size_t i = 0; i < queries.size(); ++i) {
cout << queries[i] << ':';
for (int factor : result[i]) {
cout << ' ' << factor;
}
cout << '\n';
}
return 0;
}

Complexity Analysis

Time Complexity : O(U log log U + N + F) for U ≥ 2. The sieve takes O(U log log U), and each division produces one output factor. If every query is 1, processing takes O(N) time.

Space Complexity : O(U) auxiliary space for the spf table. The returned lists take O(N + F) space.

Interview follow-up Questions

For 1, return []. For a prime such as 13, return [13] because its only prime factor is itself.

Maths

Read Similar Blogs

Comments0