Post History

Tuesday, May 28, 2013

Beginner Challenge #1: Python algorithm for prime numbers ~~Completed


With procrastination against me, I managed to finish this task. As simple as this is, I'm pretty proud of it. On the bottom you can see I am testing my Prime_finder function with a really large prime number (31,789,553) and the results came out as True.


How I completed it.

    The one special property of prime numbers is that it's a number that is only evenly divisible by itself and the number 1. In other words it has 2 divisors

   In the code I set up firstly that if the number handed was less than 2 then there's no way for it to be a prime number:
if x < 2:
return False

Then in the second part, the else statement, I set up the code so that it checks every number below  if it is divisible by that number. AND if it was, then I would count that.

for i in range(1, x + 1):
if x % i == 0:
count += 1

Lastly, at the end of the code, it checks to see how many counts there are for x. If x has more than 2 divisors, then it's not a prime number and returns False.

Could I have done this better?

Maybe.

This was a brute force attempt, and you'll notice that if you run really large numbers through this it can take up to half a minute which is quite some time in the mind of a programmer.

Thanks for reading, until next time!  

No comments:

Post a Comment