Tuesday 17 July 2012

Create a simple factor generator and prime detector with python


python programming, python how to, python tutorial, python how to generate factors and detect prime numbers
Python is a very efficient program and let's you do a lot of things with a very small coding unlike stuff like C++. I am a beginner in python and learning all the little things. With the beginner function I learned I was able to create a simple algorithm (big word!) to generate factors of a number and detect if it is prime from user input number.


Before going into any explanation (my interreption) here is the code:

n = int(input("what number you want to check? \n:"))
j = (list(range(1, n, 1)))
whylist = []
for numbers in j:
if n%numbers == 0:
whylist.append(numbers)
print("The factors are: ", whylist)

if len(whylist) == 1:
print("So, this is a prime number!")
input()

Read: Best tools to learn python with


Understanding the python factor generator


So save it with yourname.py and double click it to see if it is working. From line one, it asks a user input of a number that is converted into integer which is stored in the variable n. The method used to find factors are by dividing each number by all numbers from 1 to itself and check if the reminder is 0. If remainder is 0 that means it's a factor. To get a list of number from 1 to the given input (n) we created the second line naming the list j. Then we created another list to store the factors itself.

Next we used a for function. For the forth line the basically says: 'for' every 'numbers' in list 'j' followed by ':' to specify what to do next for the 'for'. Next line reads if n(user input) equals to 0 then (:) add the 'numbers' to the 'whylist'. The next line just prints the number out with a string.

Now detecting prime is easy with count function which will count how many elements are in the list (whylist). If the only thing found in whylist is 1 it's a prime number. We used another if statement saying if the lenth(element number) of whylist is 1, then print 'this is a prime number'. We added a input() at the end to push the program for any other input till the program ends.

I hope this post helped you with what you were looking for or helped you learn something new. If you have question leave them below and I will try my best to assist you. You might consider subscribing to this blog because future python tutorial with simple explanation like this one are on my post idea list. Have a great day.

No comments:

Post a Comment