Comments on: Prime Numbers In Python https://pthree.org/2007/09/05/prime-numbers-in-python/ Linux. GNU. Freedom. Sun, 17 Sep 2017 02:25:05 +0000 hourly 1 https://wordpress.org/?v=4.9-alpha-41386 By: nolfonzo https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-115692 Sun, 10 Apr 2011 23:26:24 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-115692 Tom I think you may need sqrt(n)+1

]]>
By: sanjo https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-115585 Fri, 18 Mar 2011 02:25:06 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-115585 Nice one, thank you. 🙂

]]>
By: Tom Jones https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-111555 Sun, 19 Dec 2010 00:38:01 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-111555 A for loop is even cleaner

from math import sqrt

def is_prime(n):
for i in range(2, sqrt(n)):
if n % i == 0:
return False
return True

]]>
By: Bismoy https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-111147 Sun, 05 Sep 2010 18:21:06 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-111147 gr8 stuff...........

]]>
By: nolfonzo https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-111146 Fri, 03 Sep 2010 18:51:59 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-111146 Using Numpy and a sieve a approach you can generate these very fast. I wrote about this on my blog recently: http://rebrained.com/?p=458

import math
import numpy
def prime6(upto):
primes=numpy.arange(3,upto+1,2)
isprime=numpy.ones((upto-1)/2,dtype=bool)
for factor in primes[:int(math.sqrt(upto))]:
if isprime[(factor-2)/2]: isprime[(factor*3-2)/2:(upto-1)/2:factor]=0
return numpy.insert(primes[isprime],0,2)

]]>
By: people https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-110977 Mon, 14 Jun 2010 16:28:31 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-110977 n=input("Enter any number-")
if n==2:
print "prime"
if n==1:
print "neither prime nor composite"
if n>2:
for i in range(2,n):
if n%i==0:
print "composite"
break
i=i+1
else:
print "prime"
else:
print "enter correct input"

]]>
By: kotireddy https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-110797 Fri, 09 Apr 2010 06:28:25 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-110797 def isPrimenumber(number):
c=0
for i in range(number):
if number%(i+1)==0:
c=c+1
if c>2:
print number,"is not prime number"
else:
print number,"is prime number"
num=raw_input("enter a number:")
num=int(num)
isPrimenumber(num)

]]>
By: Veerabhadra Rao https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-110787 Thu, 01 Apr 2010 14:46:22 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-110787 iam a iiit student in nuzvid from visakhapatnam

]]>
By: Veerabhadra Rao https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-110786 Thu, 01 Apr 2010 14:29:36 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-110786 how are you

]]>
By: lizz https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-103465 Mon, 23 Jun 2008 12:29:40 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-103465 your story is sux, try to test, for example, 99999999977 or 4740914805200312594461
try to read about miller-tabin algorythm

P.S. sorry for my english 😉

]]>
By: Johnathan Nguyen https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-86947 Fri, 28 Dec 2007 00:10:43 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-86947 Review this publication: Prime Sequence Homology by Daniel Blake et al; Fourrier University, Grenoble

Dr. Blake's approach is via a randomization channel. Code is also presented. I tried to cut and paste but was unsuccessful.

]]>
By: Francesc Dorca https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-68151 Thu, 06 Sep 2007 21:39:50 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-68151 Hi Aaron,

First of all congratulations for your interesting blog.

Let me suggest an improvement to make your code much more efficient.

I do not know Python, but using my knowledge on other programming languages I think that I can understand your code pretty well.

You can use only integer arithmetic doing two minor changes.

Eliminate the sentence

1
import math

and replace the line

1
while i <= math.sqrt(n):

by the equivalent sentence

1
while i*i <= n:

that uses only integer arithmetics.

]]>
By: Aaron https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-68143 Thu, 06 Sep 2007 19:41:53 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-68143 @Levi- Fair enough. My inexperience really shows through on things like this. I need to spend more time on math-related algorithms analyzing their complexity and what's going on under the hood I think.

Again, thanks for the info.

]]>
By: Levi https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-68139 Thu, 06 Sep 2007 18:59:50 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-68139 A couple of comments regarding the complexity of this algorithm.

First, you don't include lower-order factors in big-O notation. An algorithm that takes n-1 steps is still O(n). An algorithm that takes n^2+5n+2 steps is O(n^2), or simply Polynomial Time when speaking in terms of complexity classes.

Second, you're ignoring the fact that, for large numbers, modulo is not a constant time operation. The O(sqrt(n)) complexity is only correct if n is the size of your number and it fits in the hardware. This isn't true in general, so it's not very useful for the sorts of reasoning big-O notation was invented for.

To be general, you need to define the algorithm in terms of the number of bits in your input number. For an integer N, it takes log N + 1 bits to store it. That means that the complexity in terms of the input size is O(2^(n/2)). This is exponential, i.e. very bad. A 1024 bit integer gives you a running time of essentially 2^512, which is definitely intractable.

As other people have stated, there are much better algorithms for primality testing, and the one you're using is worthless for crypto applications.

My reference for this comment: Complexity and Cryptography: An Introduction

]]>
By: Cornelius DuLac https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-68107 Thu, 06 Sep 2007 13:03:29 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-68107 I don't think you are using the O notation correctly. Using binary search to search through a list of n ordered numbers takes O(sqrt(n)). Here, n is not the number of inputs, it's the input itself.

Now, if you were saying n was the size of the input number, I think you'll find that your notation is still flawed. This is not a poly time algorithm. If it were, you would be able to break several encryption algorithms that rely on the hardness of the primality problem, as well (I believe) P=NP.

It's been a while since I've done algorithmics in school, but I think you'll find I am right.

C.

]]>
By: Karl Lattimer https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-68074 Thu, 06 Sep 2007 09:17:18 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-68074 Careful of sweeping statements like "As far as I can tell, this is the most efficient way (not necessarily the fastest) to test if a number is prime or not."

When its hardly efficient, or elegant, and efficiency in software implies speed.

If I were to ask you whether or not 578438089702734102192371840427834912121157 were prime or not how long would it take to identify that? PGP has been implementing prime testing and deriving primes in far more efficient ways for a long time, and can determine whether or not a 4096bit number is prime in a few seconds.

Exploit sieves and "don't care" cases faster.

]]>
By: Walther https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-68050 Thu, 06 Sep 2007 05:59:19 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-68050 Hehe, as usual I got carried away and programmed multiple versions myself in Python (including a sieve algorithm and a caching version of your algorithm).
For the critics here: the simple algorithm (with the sqrt) is pretty fast at least up until (2^31)-1.
If you want to be fast for big primes, you would probably pick a different language anyway.

]]>
By: anon https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-68047 Thu, 06 Sep 2007 05:06:54 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-68047 In 2004, Agrawal, Kayal, and Saxena published this paper:
http://www.math.princeton.edu/~annals/issues/2004/Sept2004/Agrawal.pdf
in which they present a polynomial time algorithm to determine if a number is prime or composite.

Note that it is a polynomial time algorithm in the size of the input.

I hope you find that article interesting. In addition to proving a deep result, the references section will point you to just about everything you could care to know about primes.

]]>
By: anon https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-68046 Thu, 06 Sep 2007 05:01:17 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-68046 You may find this interesting:

http://www.math.princeton.edu/~annals/issues/2004/Sept2004/Agrawal.pdf

]]>
By: Jon https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-68038 Thu, 06 Sep 2007 03:57:00 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-68038 C++ version, anyone?

1
2
3
4
5
6
7
8
bool isPrime(long p)
{
  long maxfactor = static_cast(sqrt(p) + 1);        // round up
  for (long n = 2; n < maxfactor; ++n)
    if (p % n == 0)
      return false;
  return true;
}

Just for reference, to test each number in [1, 10^6], the C/C++ version is a bit more than an order of magnitude faster than the sqrt-optimized version of the above python; python (2.10 sec versus 39.5 sec).

Programming posts are always nice to see in my reader; keep up the learning!

(Side note: I can't put a less-than sign in my comment. It appears that the post page thinks its a tag start, so I tried < but that shows literally, as seen above.)

]]>
By: Charles McCreary https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-68034 Thu, 06 Sep 2007 03:26:02 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-68034 Your post got me thinking about python and optimizations. So I googled about and found a few algorithms that are pretty fast at determining primeness. I posted them here: http://www.tiawichiresearch.com/?m=200709

]]>
By: Xyhthyx https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-68022 Thu, 06 Sep 2007 02:20:11 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-68022 Perl version anyone?

sub is_prime {
my ($n) = @_;
$n = abs($n);
my i = 2;
while ($i

]]>
By: Aaron https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-68010 Thu, 06 Sep 2007 00:16:57 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-68010 @rbu- Ahh, good call. Makes perfect sense.

@Swistak- As I mentioned in the post, there are probably faster algorithms.

@Rocco Stanzione- No problem. Keep posting. 🙂 Thanks for the code, by the way.

@Pansen & randomwalker- Thanks for the informative comments. Very well thought through.

]]>
By: Rocco Stanzione https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-68008 Wed, 05 Sep 2007 23:53:26 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-68008 Last post I promise! Sure there are plenty of faster algorithms. But this is reasonably fast, reasonably efficient and accomplished with reasonably little code. It's also very useful for both testing primeness and enumerating primes. Anyway I made it faster still and more accurate (1 is not a prime number). This enumerated all the primes from 1 to 1M in 34 seconds for me:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Integer
  def is_prime?
    i=3
    return false if self % 2 == 0 and self != 2
    ss = sqrt(self).floor
    return false if ss**2 == self
    while i &lt;= ss
      return false if self % i == 0
      i += 2
    end
    return true
  end
end
]]>
By: randomwalker https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-68006 Wed, 05 Sep 2007 23:47:39 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-68006 Seriously, WTF? This is the opposite of slick.

]]>
By: Pansen https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-68004 Wed, 05 Sep 2007 23:16:50 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-68004 what are you talking about? this is very trivial code that is not even remotely efficient at what it's supposed to do.

]]>
By: Rocco Stanzione https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-68003 Wed, 05 Sep 2007 23:12:26 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-68003 Also rbu is right, doing while i <= sqrt(n) (or sqrt(self) in my ruby) it's very much faster.

]]>
By: Rocco Stanzione https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-68002 Wed, 05 Sep 2007 23:07:23 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-68002 Good stuff! I rubified it and started playing with it, and sped it up thusly (don't forget to change the &lt; back to a <, your software hates it):

1
2
3
4
5
6
7
8
9
10
11
class Integer
  def is_prime?
    i=3
    return false if self % 2 == 0 and self != 2
    while i &lt; self/2
      return false if self % i == 0
      i += 2
    end
    return true
  end
end
]]>
By: Swistak https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-67996 Wed, 05 Sep 2007 22:30:52 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-67996 There are A LOT faster algorithms doing that job. They make use of number theory and work in polynomial time (in terms of number length)

]]>
By: rbu https://pthree.org/2007/09/05/prime-numbers-in-python/#comment-67995 Wed, 05 Sep 2007 22:17:21 +0000 http://www.pthree.org/2007/09/05/prime-numbers-in-python/#comment-67995 One simple optimization: The while loop can stop when i > sqrt(n). If no factors were found until then, there won't be any in (sqrt(n),n].
Other optimizations include not testing every single number as divisor, but only new prime numbers. Check the Sieve of Eratosthenes for details.

--rbu

]]>