Re: finding primes
- From: Pascal Bourguignon <pjb@xxxxxxxxxxxxxxxxx>
- Date: Fri, 27 Oct 2006 15:03:06 +0200
"Digital Puer" <digital_puer@xxxxxxxxxxx> writes:
Got this on an interview question: given two integers A and B,
find all primes between them.
I basically wrote an initial function, bool isPrime(int i), which
loops over all numbers between 2 and sqrt(i) to see if i%num == 0,
in which case the number is not a prime. With this function I loop
between A and B, calling isPrime() on each value.
Is there a better way to do this? I looked at the Sieve of
Eratosthenes,
which didn't seem to be much better.
Complexity of euclidian gcd(a,b) is O(log(max(a,b))).
gcd(a,b) is the product of all the primes between a and b.
So it only remains to factorize this one number, instead of
factorizing both a and b, for which you have to compute the primes
only up to sqrt(gcd(a,b)) at most.
O(sqrt(gcd(a,b))+log(max(a,b)))
--
__Pascal Bourguignon__ http://www.informatimago.com/
"Do not adjust your mind, there is a fault in reality"
-- on a wall many years ago in Oxford.
.
- References:
- finding primes
- From: Digital Puer
- finding primes
- Prev by Date: enqueue data structure
- Next by Date: Re: finding primes
- Previous by thread: Re: finding primes
- Next by thread: Re: finding primes
- Index(es):
Relevant Pages
|