Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating time complexity for finding first 'n' prime numbers

The algorithm for finding first 'n' prime numbers is:

while (number <= n) {
  boolean isPrime = true; 
  for (int divisor = 2; divisor <= (int)(Math.sqrt(number)); divisor++) {
    if (number % divisor == 0) {
      isPrime = false;      
      break;
    }
  }
  if(isPrime) 
    System.out.print(number + " ");
}

The book, "Introduction to java programming", calculates big-O for this algorithm as:

Since it takes √i steps in the for loop to check whether number i is prime, the algorithm takes √2 + √3 + √4 + ... + √n steps to find all the prime numbers less than or equal to n.

Observe that,

√2 + √3 + √4 + ... + √n <= n√n

Therefore, the time complexity for this algorithm is O(n√n).

Que:

1. He says, "it takes √i steps in the for loop to check whether number i is prime".

Don't you think it should be (√i-1) steps.

2. Please explain how

√2 + √3 + √4 + ... + √n <= n√n

(I know the relationship holds if you just replace 'n' with a random number. I need explanation)

like image 299
Wololo Avatar asked Aug 28 '15 12:08

Wololo


People also ask

What is the time complexity of finding prime numbers?

Time Complexity: O(sqrt n) because recursive function will call itself at most sqrt(n) times.

What is the best algorithm for finding a prime number?

A prime sieve or prime number sieve is a fast type of algorithm for finding primes. There are many prime sieves. The simple sieve of Eratosthenes (250s BCE), the sieve of Sundaram (1934), the still faster but more complicated sieve of Atkin (2003), and various wheel sieves are most common.


2 Answers

  1. Complexity-wise, subtracting 1 has no effect (and this is an informal introduction).
    (It's actually floor(√n) - 1.)
  2. You have n - 1 terms. Adding √n n - 1 times:

    √n + √n + √n + ... + √n = (n-1)√n <= n√n

and since √2, √3, √4, ... are all less than √n, it follows that

√2 + √3 + √4 + ... + √n <= √n + √n + √n + ... + √n <= n√n
like image 73
molbdnilo Avatar answered Sep 21 '22 01:09

molbdnilo


answer 2 :

for 0 < i <= n we have i <= n, therefore √i <= √n, so the sum of √i for i between 1 and n <= the sum of √n between 1 and n which √n + √n ... + √n, n times

like image 44
Steve Marion Avatar answered Sep 18 '22 01:09

Steve Marion