4

I have to find total number of factors for all numbers from 2 to N.

Here's my approach.

Run Sieve of Eratosthenes and get all primes from 2 to N.

For each number from 2 to N, do the prime factorisation and get the exponents of all the prime factors. Add 1 to each prime factor exponent and multiply all the exponents i.e.,

N = 2^x1 * 3^x2 * 5*x^3 ...

Then,

Number of factors = (x1 + 1) * (x2 + 1) * (x3 + 1) ...

Is there any alternative/efficient way with which I can efficiently calculate total number of factors for first N natural numbers.

Sai Nikhil
  • 1,237
  • 2
  • 15
  • 39

1 Answers1

6

The number of factors of all integers between 2 and N can be calculated in O(N) via the following formula:

total = N/1 + N/2 + ... + N/N - 1. (integer division)

Any particular integer x between 2 and N is a factor of the following integers between 2 and N: x, 2x, 3x, 4x, ..., (N/x)x

Example 1, the total number of factors of the numbers from 2 to 6 is 13: 6/1 + 6/2 + 6/3 + 6/4 + 6/5 + 6/6 - 1 = 6+3+2+1+1+1-1 = 13

These are the factors:
2: 1, 2
3: 1, 3
4: 1, 2, 4
5: 1, 5
6: 1, 2, 3, 6

2, 3, and 5 all have 2 factors, 4 has 3, and 6 has 4, for a total of 13.

If you just want the prime factors:

total = N/p1 + N/p2 + ... + N/pk where pk is the largest prime <= N.

E.g., N=6: 6/2 + 6/3 + 6/5 = 6

2: 2
3: 3
4: 2
5: 5
6: 2, 3
Dave
  • 7,460
  • 3
  • 26
  • 39
  • 3
    The OP wants all the factors, as the formula for `Number of factors` in the question shows. Your algorithm is outstanding, +1. But your explanation in the last paragraph could be better. And you could avoid the final subtraction by `1` by doing your sum only up to `N/(N-1)` and leaving out both the `N/N` and the `-1`. – Rory Daulton Jan 27 '19 at 22:37
  • The question asks for number of factors, and OP's formula clearly states that he wants to find number of factors. https://brilliant.org/wiki/factors/. And if you want to find all factors, if you run through all number from 1 to N, the timecomplexity will be worse than what the OP's currently have, which is O(N^2). – Pham Trung Jan 28 '19 at 10:47
  • This is O(N^2). Doesn't scale good for large 'N'. Is there any way we can optimize this? – Sai Nikhil Jan 28 '19 at 10:55
  • 2
    @PhamTrung: This algorithm is not O(N^2), it is O(N). There are N integer divisions, N-1 additions, and 1 subtraction (in Dave's original form). The point of Dave's algorithm is that is does not ever find the factors of any number--they end up being counted in a different, shorter way. Dave's algorithm does work correctly--I tested it for all values of `N` up to 10,000, comparing his result with a more straightforward, slower way. I deleted my own answer because his is so much better. – Rory Daulton Jan 28 '19 at 11:19
  • @SaiNikhil This is O(N), as Rory explains above. – Dave Aug 06 '21 at 03:28