Posts: 401
Threads: 141
Joined: Oct 2009
Reputation:
5
02-23-2010, 01:54 PM
(This post was last modified: 02-23-2010, 01:56 PM by nevets04.)
I made this function to check whether a number was prime or not.
This was developed using codepad.org to test it during my 15 minute study hall. So it's simple, but it does work as far as I can see.
Code: #!/usr/bin/env python
def isprime(n):
if n > 10:
if n%2 == 0 or n%3 == 0 or n%4 == 0 or n%5 == 0 or n%6 == 0 or n%7 == 0 or n%8 == 0 or n%9 == 0 or n%10 == 0:
return False
else:
return True
if n <= 10:
if n == 2 or n == 3 or n == 5 or n == 7:
return True
if n == 1 or n == 4 or n == 6 or n ==8 or n == 9 or n == 10:
return False
Posts: 245
Threads: 33
Joined: Oct 2009
Reputation:
10
Seems to be effective, you could have shortened it a bit though
Code: #!/usr/bin/env python
def isprime(n):
if n > 10:
for x in range(2, 11):
if n%x == 0: return False
else:
return True
if n <= 10:
if n in (2, 3, 5, 7): return True
if n in (1, 4, 6, 8, 9, 10): return False
I can see your a little rusty
Posts: 103
Threads: 7
Joined: Oct 2009
Reputation:
5
(02-23-2010, 06:46 PM)uber1337 Wrote: Code: if n in (2, 3, 5, 7): return True
if n in (1, 4, 6, 8, 9, 10): return False
I can see your a little rusty
Code: return False if n in [1, 4, 6, 8, 9, 10] else True
You are aswell
Terrorcore, unleash, extermination
Hyper real, cold blood, determination
fudge them, I like this sensation
Incredible, I from the annihilation
Posts: 245
Threads: 33
Joined: Oct 2009
Reputation:
10
(04-05-2010, 06:15 PM)Fallen Wrote: Code: return False if n in [1, 4, 6, 8, 9, 10] else True
You are aswell LOL you really need to stop shortening things lol. Why don't you just use C++ and have a full length program on one line?
Posts: 1
Threads: 1
Joined: Feb 2010
Reputation:
0
04-18-2010, 11:08 AM
(This post was last modified: 04-18-2010, 11:10 AM by symetrik.)
Quote:Code: #!/usr/bin/env python
def isprime(n):
if n > 10:
for x in range(2, 11): if n%x == 0: return False
else: return True
if n <= 10: return False if n in [1, 4, 6, 8, 9, 10] else True
Defeated by:
Code: if isprime(x) and x > 11: isprime(x**x)
For example:
Code: if isprime(13) and x > 11: # Will return true, as 13 is a prime and is larger than 10.
isprime(13**13) # As 13 is not in the check list, this number will be found to be a prime, even though it clearly is not.
Posts: 43
Threads: 6
Joined: Oct 2009
Reputation:
0
05-05-2010, 05:30 PM
(This post was last modified: 05-05-2010, 05:34 PM by wat.)
Your function assumes that all composite numbers above 10 are divisible by a number smaller than 10; not true.
Here's an article explaining some of the intricacies that go into finding prime numbers .
Keep in mind that the first method mentioned could be optimized more by only checking numbers smaller than sqrt(num) instead of num / 2.
|