Python Forum
Quick prime numbers function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Quick prime numbers function
#1
EDIT: NOT WORKING AS EXPECTED.

Hi all!
Im pretty new at python programming, been practicing as much as I can in sites as practice-python, Project Euler and others...

Prime numbers are very common in Beginner level practicing so I made a very simple function that get a number and return True for prime numbers and False for others.

#This function gets a number (up to 16 digits) and checks if its a prime number.
#Returns True for prime number, False for others.

def isPrime(number):
  Option1 = (number - 1) / 6
  Option2 = (number + 1) / 6

  if Option1.is_integer() or Option2.is_integer():
    return True
  else:
    return False
    
  
Tell me what you think about it :)

Thanks!
Reply
#2
Your primality test is too limited to be practical but the concept is good.

Your test fails for:
- Says that 1 is prime when is not
- Says that 2 and 3 are not prime
- For squares of a prime (like 25 or 49) also fails as it thinks they are prime

Also mixing integer and float arithmetic is not a good idea as you will depend on the rounding... to implement your function only with integer arithmetic you an use the modulo operation, and as the input number can be really big, is better to do it once.
Your are checking that the number - 1 is divisible by 6 and that the same as saying that the number is equal 5 modulo 6. The other check is equivalent to say that the number is equal 1 modulo 6.
So a code that performs the same as your function is:
def mayBePrime(number):
    r = number % 6
    return r == 1 or r == 5
But as I said before, as primality test is not really practical. If you want to have something solid you can implement the Baillie–PSW primality test. The programming part is easy (just some care with the division, remember to use // for integer division) and you will learn a lot about math...
Reply
#3
Oh well, my bad.
I was so furious to check it with high numbers so I missed with the sqaure of primes :/
About numbers 1 , 2 and 3 I've noticed the function doesn't take care of them...

I'll read more about Lucas-Lehmer test.
Thank you!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  The infinite sequence of prime numbers Gribouillis 4 2,803 Feb-11-2022, 08:49 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020