Prime factorisation of a Number

Maths Sieve of Eratosthenes Hard

You are given an integer array queries of length n.

Return the prime factorization of each number in array queries in sorted order.

Examples:

Input : queries = [2, 3, 4, 5, 6]

Output : [ [2], [3], [2, 2], [5], [2, 3] ]

Explanation : The values 2, 3, 5 are itself prime numbers.

The prime factorization of 4 will be --> 2 * 2.

The prime factorization of 6 will be --> 2 * 3.

Input : queries = [7, 12, 18]

Output : [ [7], [2, 2, 3], [2, 3, 3] ]

Explanation : The value 7 itself is a prime number.

The prime factorization of 12 will be --> 2 * 2 * 3.

The prime factorization of 18 will be --> 2 * 3 * 3.

Input : queries = [15, 20]

Constraints

  • 1 <= n <= 105
  • 2 <= queries[i] <= 2*105

Hints

  • A brute-force approach iterates through each number in queries and finds prime factors by checking divisibility from 2 to sqrt(num). This runs in O(n√m) (where m is the largest number in queries), which is inefficient for large numbers.
  • "A better approach is the Modified Sieve of Eratosthenes, which: Precomputes the smallest prime factor (SPF) for all numbers up to the max(queries). Uses SPF to quickly factorize numbers in O(log m) time per number instead of checking divisibility repeatedly."

Company Tags

eBay Splunk Salesforce Medtronic Walmart AMD KPMG Etsy Activision Blizzard Riot Games Western Digital Siemens Healthineers Epic Games Visa Alibaba Pinterest Rakuten Flipkart Texas Instruments HashiCorp Seagate Technology Swiggy Boston Consulting Group Morgan Stanley Lyft Google Microsoft Amazon Meta Apple Netflix Adobe