查找给定范围内具有素数的除数的总数

时间:2013-11-04 15:20:18

标签: sieve-of-eratosthenes sieve primality-test sieve-of-atkin

范围从1到1,000,000,000,000。 输入:L和R,其中L-R <= 1,000,000 L和R可以是1到1,000,000,000,000之间的任何值。

例如,如果L = 2且R = 5 那么O / P:4

原因:

2 - 1,2总计2是素数

3- 1,3总计2是素数

4- 1,2,3总计3是素数

5- 1,5总计2是素数

因此范围内的4个数字具有素数。所以输出是4。

我尝试过使用筛子,但耗费时间。你能给我一个更好的解决方案吗?

1 个答案:

答案 0 :(得分:0)

方法1:

1. Calculate all prime numbers in the given range (2,R) using 
   sieve of eratosthenes.
2. Initialize the result as number of primes(say NP) since all primes 
   are having prime number(2) of divisors.
3. For each prime((P), we can generate maximum of NP - 1 numbers 
   that has prime number of divisors. 

    Let say P1,P2,P3,....Pn are prime numbers of range (L,R).

    NP is the number of primes of range (L,R).

    Each prime has 2(prime number of) divisors.
    Square( 3 - 1) of prime has 3 divisors.
    4th power( 5 - 1) of prime has 5 divisors.
    ...
    nth power( n + 1 (is prime) - 1) of prime has n+1 divisors.

    Increment the result by 1 if pow(Pi, Pj -1) <= R, i >= L, j<=R and i != j

Note : All primes in an array(AP) are increasing numbers(sorted), so we can 
       also use the modified binary search to find the numbers of 
       prime divisors in a given range

方法2 :(由我的同事建议并由我改进)

1. Create a divisors array that can hold R - L - 1 number of elements and 
   initialize it to zero.
2. Iterate i from L to R
3.  Check if divisors(i) <> 0. Go to step 2 if divisors(i) = 0.
4.  compute the absolute difference of number of divisors of i and i * p (prime).
5.  The absolute difference between the number of divisors of i, i * p and
    i*p, i*p*p are same.
        a = number of divisor of i
        d = difference of number of divisors of i * 2 and i.
        divisors(i-L) = a
        p = 2(prime number)
        n = distance from a in arithemetic progression
        iterate j from i * p to R, j = j * p
            divisors(j-L) = a + n * d
            n = n + 1
6) Filter divisors array to find prime number of divisors