what will be the best way to find a prime number so that the time complexity is much reduced.
-
5Are you looking for prime numbers, or are you looking to test if a number you have is prime? – fbrereto Sep 15 '09 at 18:10
-
28"2". Now you're done for all time. – RBarryYoung Sep 15 '09 at 18:11
-
5Unless, you had some, you know, "requirements" or "specifications". – RBarryYoung Sep 15 '09 at 18:12
-
finding prime numbers between range of numbers.. say between 1 and 99999.. – d3vdpro Sep 15 '09 at 18:14
-
4there are approximately 1000 duplicates of your question along with an answer at SO, and millions more to find via google – DaClown Sep 15 '09 at 18:28
-
Do you want to be absolutely sure they're prime, or will you be happy if they're just almost certainly prime? (For large numbers, the latter is far faster.) Do you want to find all primes in a given range, or just some of them? What ranges did you have in mind? What's about the highest number (order of magnitude would be fine) you'd be interested in? – David Thornley Sep 15 '09 at 18:54
-
1Build a list of primes first. Then you can use this list for future references. – Wim ten Brink Sep 15 '09 at 19:11
9 Answers
When it comes to finding prime numbers, the Sieve of Eratosthenes and the Sieve of Atkin are two possible solutions. The Sieve of Eratosthenes has a complexity of O((n log n)(log log n)). The Sieve of Atkin has a complexity of O(N / log log n).
If you have a number and you want to find out if it's prime, that is called performing a primality test. The naive approach is to check all numbers m from 2 to sqrt(n) and verify that n % m is not 0. If you want to expand this slightly, you can throw out all even numbers (except 2). There are also some other enhancements to this naive approach that might improve performance, along with other, more advanced techniques.

- 114,398
- 98
- 311
- 431
-
5
-
2
-
Jonathan - Thanks for pointing that out. I edited the post to reflect that. – Thomas Owens Sep 15 '09 at 21:51
-
@ThomasOwens What is reason for checking from 2 to sqrt(n) in the naive approach ? – Geek Aug 14 '12 at 04:55
-
@Geek If the number was not prime, at least one factor must be below sqrt(n). Assuming you're not trying to factor the number, it doesn't matter what all of the factors are. You just need to know that some factor exists. – Thomas Owens Aug 14 '12 at 10:29
-
1The usually implemented basic versions of the algorithms are at asymptotic computation complexities of O(n log log n) and O(n) for the Sieve of Eratosthenes and the Sieve of Atkin, respectively. The SoE figure used in this answer doesn't apply to the same algorithm but rather to some sort of incremental algorithm using perhaps a Priority Queue. The SoA figure is often quoted for an esoteric theoretical modification of the basic SoA algorithm that I don't believe has ever been implemented, even by its authors (Their reference primegen SoA implementation has a theoretical O(n) performance). – GordonBGood Apr 03 '15 at 06:20
Use sieve of Eratosthenes is if you want to enumerate primes. If you want to generate a large prime, generate a random odd number and check for primality.

- 32,009
- 9
- 68
- 103
-
Wikipedia points to the Sieve of Atkin as being more efficient than the Sieve of Eratosthenes... – Thomas Owens Sep 15 '09 at 18:14
-
-
+1. The Sieve of Eratosthenes is supposed to be fairly easy to implement, although I've never done so...perhaps I will, just to see. It might not be the best performer, but from what I can tell, it's usually good enough. – Thomas Owens Sep 15 '09 at 18:23
-
1@ThomasOwens, the WP article indicates that the Sieve of Atkin is more efficient based on asymptotic computation complexity of O(n log log n) for the Sieve of Eratosthenes and O(n) for the SoA. In fact, the new edited articles show that although the basic SoA uses a constant about 0.258717... times the range operations, for many ranges up to extremely high practical limits, a maximally wheel factorized SoE actually has less operations and the operations are simpler. Thus, a maximally wheel factorized and optimized SoE for equivalent complexity as the SoA is likely never slower than SoA. – GordonBGood Apr 03 '15 at 06:12
If it's below a certain range, best way would be to look it up in a precomputed list. There's plenty of them, up to very high numbers.
Example, all the primes up to 10,000,000,000 at http://www.prime-numbers.org/

- 76,767
- 18
- 98
- 146
Inspired by xkcd:
int findPrimeNumber() {
return 2; // guaranteed to be prime
}

- 125,917
- 54
- 300
- 447
-
3If you're going to post a purely humorous answer to a serious question, at least make it community wiki. – Mark Ransom Sep 15 '09 at 18:29
-
2I would come back with the smart-alecky response that this IS a serious answer... but really I just didn't know you could make answers community wiki (and that I honestly did not expect any upvotes for such a ridiculous answer). – Dan Tao Sep 15 '09 at 18:33
-
1
-
3To be honest, it does satisfy the OP's request. However, my finely honed sense of telepathy, gained by trying to get requirements out of users without violating the Hague and Geneva Conventions, suggests that this isn't all the OP wants. – David Thornley Sep 15 '09 at 18:51
-
huh, would you look at that, you can make answers CW now! How long have I been blind to that feature? – Matt Sep 15 '09 at 20:06
-
If you want to generate primes from 1 to whatever, then the fastest way is probably a wheeled Sieve as implemented here, which can typically test more than 3,000,000 candidate primes a second on an average laptop (and that's using an unoptimized language like VB.net), and factor the non-primes to boot. In c++ it could be easily 5 to 20 times faster.

- 1
- 1

- 55,398
- 14
- 96
- 137
-
Although I'm not a fan of VB.NET, the "5-20" times faster seems a little over the top. But... +1 for the link – Philippe Leybaert Sep 15 '09 at 18:37
-
Granted it's hard to say: but my understanding is that VB.net does no loop, etc. code-type optimizations and this program/algorithm is *exactly* the kind of algorithm can go gangbusters on. OTOH, if it were making heavy use of non-replaceable .NET calls, then the difference would be a lot less. – RBarryYoung Sep 15 '09 at 18:40
-
(wish I was more proficient in VC++, I'd just re-code it and see what the difference was). – RBarryYoung Sep 15 '09 at 18:43
-
OTOH .NET uses jit which for a repetetive task like this should be able to optimize quite a bit. – Esben Skov Pedersen Sep 15 '09 at 19:16
-
-
1RBarryYoung, see "Is Managed Code Slower Than Unmanaged Code?" http://www.grimes.demon.co.uk/dotnet/man_unman.htm – Alex Budovski Dec 05 '09 at 04:23
Although there are more efficient algorithms, the Miller-Rabin primality test is one of the simplest tests to implement.

- 25,523
- 18
- 82
- 173
There are two different questions:
1) How to find if a number
is a prime number? If you discover an efficient algorithm for this one, you will be famous for the next 2000
years ;)
2) How to find the prime numbers
up to a limit N
?
probably this is what you are asking about. Sieve of Atkin
is the most efficient one If your range or limit N
is really big number. In reasonable ranges, you could implement an optimized variation of Sieve of Eratosthenes. I found these two sites to be more than useful:
EDIT: @avakar
While I am more than beginner on the subject, I don't think AKS
is the waited algorithm! From the same source:
However, some composite numbers also satisfy the equivalence. The proof of correctness for AKS consists of showing that there exists a suitably small r and suitably small set of integers A such that if the equivalence holds for all such a in A then n must be prime.

- 94,250
- 39
- 176
- 234
-
There is an efficient (as in polynomial) algorithm: http://en.wikipedia.org/wiki/AKS_primality_test – avakar Sep 15 '09 at 19:08
-
-1: There already *are* extremely efficient algorithms for this. Sub-linear, for serial tests. – RBarryYoung Sep 16 '09 at 02:06
-
What is described in the "Black Key Sieve" is just a primitive version of a wheeled sieve. – RBarryYoung Sep 16 '09 at 02:09
-
(took the -1 back, considering there is some explanation of the differences) – RBarryYoung Sep 16 '09 at 02:10
-
AraK, AKS will polynomially and deterministically determine whether an integer is a prime. The two sentences you cited merely point out what must be proven in order for the algorithm to be considered correct. (And the original paper provides the proof.) – avakar Sep 16 '09 at 15:00
-
1The Sieve of Atkin is not the best algorithm for finding a sequence of primes for a very big range - there is no practical proof it is: 1) It can be shown as per the new WP Sieve of Eratosthenes article that a maximally wheel factorized SoE has less operations than the SoA for any practical range using a "one huge memory array" model, and 2) Atkin and Bernstein's reference "primegen" implementation of the SoA gets very slow for large ranges as compared to a maximally wheel factorized (and optimized) SoE primesieve due to inefficiencies in "prime squares free" as spans exceed buffer range.. – GordonBGood Apr 03 '15 at 06:31
Take a look at existing libraries e.g. OpenSSL and GNU MP.
I found a way.But may its lengthy, but its perfect ..no flaws in it.
package javaapplication4;
import java.io.*;
import java.util.*;
public class Main
{
static Vector vprime = new Vector();
static Vector vnotprime = new Vector();
static Vector newVect = new Vector(new LinkedHashSet());
static TreeSet<Integer> st = new TreeSet<Integer>();
static int n = 0;
static int starr[];
void prime()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter number to begin");
int beg = sc.nextInt();
System.out.println("Enter number to end");
int end = sc.nextInt();
try
{
for (int i = beg; i <= end; i++)
{
if (i == 1)
{
vnotprime.add(i);
st.add(i);
}
if (i == 2)
{
vprime.add(i);
}
if (i%2 != 0 && i%(Math.sqrt(i)) != 0)
{
vprime.add(i);
}
if (i%2 == 0 && i != 2)
{
vnotprime.add(i);
st.add(i);
}
if (i%(Math.sqrt(i)) == 0)
{
vnotprime.add(i);
st.add(i);
}
/*if (i%(Math.sqrt(i)) == 0 && i != 1)
{
vnotprime.add(i);
}*/
}
}
catch(Exception ex)
{
System.out.println("Enter proper value");
}
}
void showprime()
{
System.out.println("Prime Numbers are");
Iterator it = vprime.iterator();
while (it.hasNext())
{
System.out.println(it.next());
for (int i : st)
{
}
}
}
void shownonprime()
{
System.out.println("these are non-Prime Numbers are");
Iterator it = st.iterator();
int len = st.size(), k = 0;
starr = new int[len];
while (it.hasNext())
{
System.out.println(it.next());
}
for (int i:st)
{
starr[k++] = i;
}
}
public static void main(String[] args) throws IOException, Exception
{
Main m = new Main();
m.prime();
m.showprime();
m.shownonprime();
for(int i = 0; i < starr.length; i++)
{
System.out.println("I got it " + starr[i]);
}
}
}

- 16,827
- 6
- 51
- 95