Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return all prime numbers smaller than M

Given an integer M. return all prime numbers smaller than M.

Give a algorithm as good as you can. Need to consider time and space complexity.

like image 540
user658266 Avatar asked Mar 18 '11 02:03

user658266


People also ask

How many prime numbers are less than a million?

List of prime numbers less than one million. In fact, there are 78,498 prime numbers less than 1,000,000=one million.

What is prime number M?

A prime number is a whole number greater than 1 whose only factors are 1 and itself. A factor is a whole number that can be divided evenly into another number. The first few prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29. Numbers that have more than two factors are called composite numbers.

Can you list all prime numbers that are less than 100?

The prime numbers from 1 to 100 are: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97. Why is 1 not a prime number?


2 Answers

The Sieve of Eratosthenes is a good place to start.

http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

like image 151
Andrew Cooper Avatar answered Nov 11 '22 11:11

Andrew Cooper


A couple of additional performance hints:

  1. You only need to test up to the square root of M, since every composite number has at least one prime factor less than or equal to its square root
  2. You can cache known primes as you generate them and test subsequent numbers against only the numbers in this list (instead of every number below sqrt(M))
  3. You can obviously skip even numbers (except for 2, of course)
like image 26
Wayne Avatar answered Nov 11 '22 12:11

Wayne