•
•
•
•
What is DaniWeb IT Discussion Community?
You're currently browsing the Python section within the Software Development category of DaniWeb, a massive community of 402,505 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,793 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our Python advertiser: Programming Forums
This simple isprime(number) function checks if the given integer number is a prime number and returns True or False. The function makes sure that the number is a positive integer, and that 1 is not considered a prime number.
Last edited : Apr 28th, 2007.
# prime numbers are only divisible by unity and themselves # (1 is not considered a prime number by convention) def isprime(n): '''check if integer n is a prime''' # make sure n is a positive integer n = abs(int(n)) # 0 and 1 are not primes if n < 2: return False # 2 is the only even prime number if n == 2: return True # all other even numbers are not primes if not n & 1: return False # range starts with 3 and only needs to go up the squareroot of n # for all odd numbers for x in range(3, int(n**0.5)+1, 2): if n % x == 0: return False return True # test ... print isprime(1) # False print isprime(2) # True print isprime(3) # True print isprime(29) # True print isprime(345) # False print isprime(999979) # True print isprime(999981) # False
Comments (Newest First)
slate | Light Poster | Jun 7th, 2008
•
•
•
•
Simple RSA primtest. Does not work on universal pseudo primes.
python Syntax (Toggle Plain Text)
def isprime(n,PROB): '''returns if the number is prime. Failure rate: 1/4**PROB ''' if n==2: return '1' if n==1 or n&1==0:return '0' s=0 d=n-1 while 1&d==0: s+=1 d>>=1 for i in range(PROB): a=random.randint(2,n-1) composit=True if pow(a,d,n)==1: composit=False if composit: for r in xrange(0,s): if pow(a,d*2**r,n)==n-1: composit=False break if composit: return False return True
Toster | Newbie Poster | Jun 3rd, 2008
•
•
•
•
I think the mistake is that you converted the square root to an int, because the code I wrote a couple of years ago works fine, and its almost the same
python Syntax (Toggle Plain Text)
def isprime(n): if n == 2: return 1 if n % 2 == 0: return 0 max = n**0.5+1 i = 3 while i <= max: if n % i == 0: return 0 i+=2 return 1
theApprentice() | Newbie Poster | Sep 19th, 2007
•
•
•
•
Hi,
The code listed above does not seem accurate as numbers like 49 and 95 pass the test and yet they are not prime numbers!
Perhaps a flaw in the algorithm used?
The code listed above does not seem accurate as numbers like 49 and 95 pass the test and yet they are not prime numbers!
Perhaps a flaw in the algorithm used?
vegaseat | Kickbutt Moderator | Apr 28th, 2007
Post Comment
•
•
•
•
DaniWeb Marketplace (Sponsored Links)