Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
isprime function
#1
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
Reply
#2
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 Tongue
[Image: izsyo6.jpg]


Reply
#3
(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 Tongue

Code:
return False if n in [1, 4, 6, 8, 9, 10] else True

You are aswell Tongue
[Image: nv70ad.png]
Terrorcore, unleash, extermination
Hyper real, cold blood, determination
fudge them, I like this sensation
Incredible, I from the annihilation
Reply
#4
(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 Tongue
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?
[Image: izsyo6.jpg]


Reply
#5
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.
Reply
#6
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 Smile.

Keep in mind that the first method mentioned could be optimized more by only checking numbers smaller than sqrt(num) instead of num / 2.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Basic filter function uber1337 1 821 08-13-2010, 10:59 AM
Last Post: xerotic

Forum Jump:


Users browsing this thread: 1 Guest(s)