Problem Link - Majin Vegeta Practice Problem in 1400 to 1600 difficulty problems
Problem Statement:
Given an integer range [n, m] for each test case, the energy required to move between two consecutive levels n and n+1 is determined by the number of distinct prime factors of n. So, for each level n, we need to compute the number of distinct prime factors and sum them up for all levels between n and m inclusive.
Approach:
Prime Factorization:
- The energy used to move from level
nton+1is equal to the number of distinct prime factors ofn. For example: Forn = 6, the prime factors are{2, 3}, so the energy used is 2.
Sieve of Eratosthenes is typically used for finding primes, but here we will modify it to count the number of distinct prime factors for each number.
Precompute the number of distinct prime factors for all numbers up to 10^6:
- Create an array
prime_factors_countwhereprime_factors_count[i]holds the number of distinct prime factors ofi. - Initialize the array as zero, then for each prime
i, increment the count of prime factors for all multiples ofi.
Sum the Distinct Prime Factors:
- For each test case, simply sum the values in
prime_factors_countfromntom.
Complexity:
- Time Complexity: The modified Sieve of Eratosthenes runs in
O(MAX log log MAX)time, which is efficient forMAX = 10^6. For each test case, we simply sum the values fromprime_factors_count[n]toprime_factors_count[m], which takesO(m - n + 1)time. In the worst case, this isO(MAX)for a single test case. - Space Complexity: We use an array
prime_factors_countof sizeMAX + 1, so the space complexity isO(MAX).