Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Tuesday, 28 August 2012

Creating a Prime Checker

For this post I will be utilising Fermat's Little Theorem to check for primes from a certain number to another number, of course you can make it check just one number if you so wish. If you do not want to program it yourself you can feel free to just download my .exe prime checkerdownload my source code or you may want to download my list of the first 7,000,000 prime numbers created with this prime checker.

I will be using
Python to create this for a few reasons but the most important of these is that Python is very useful in the sense that it does not cap the size of a number you wish to store - which is vitally important for this program as the numbers will get very, very large. Before I start you may want to read some of my posts on basic programming in Python:

  • Introduction to Python
  • Python: Mathematical Terminology
  • Python: Interaction and Variables

  • Fermat's little theorem is that ap-1/p always has a remainder of 1 for a prime p that is co-prime to a. And utilising this fact is how we check for a number being prime or not. One problem with Fermat's little theorem is that it can also occasionally work for when p is not actually prime (this is called a Poulet number), these are rare but to minimise the probability that the number isn't actually prime is to check the number with a different value of a multiple times.

    Before we begin we need to be able to check what the highest common factor of two numbers actually is (in this case it will be a and p). To do this we will use the Euclidean algorithm, if you read that post it will tell you how to create that function and also what each part means. For the purposes of this program I will simply give you the code needed.

    def gcd(a,b):
     
           while b != 0:
     
                   a, b = b, a%b
     
           return a
    Now we get down to the good bit and properly begin programming the prime checker!
    def primecheck(num):
             count = 0
             a = 2
             prime = True
    We begin by creating a new user-defined function called 'primecheck', it will require one variable, which we will call 'num'. Python uses indentation to distinguish between different code segments and functions, so everything contained within the function will be indented. Three local variables will be required for the function, one to be used as a counter for when repeating Fermat's prime check to reduce the chance that the number is a Poulet number, one to be used as the 'a' in Fermat's little theorem and one to return whether the number is prime or not.
    if (num - 1)/6 == int((num-1)/6) and (num - 5)/6 == int(num - 5)/6):
           {Fermat's prime check}
    else:
            prime = False
    return prime
     
    Now that we have the local variables for the function we can begin writing the code needed to check if a number is prime or not. The algorithm itself takes a fairly long time, so we want to begin by trying to get rid of numbers that are obviously not prime without needing to do very much to the number. All prime numbers (other than 2 and 3) can be written in the form 6n + 1 or 6n + 5 (why?), so we can check that our number satisfies this before we proceed with the more processor heavy check.

    If the number cannot be expressed in the form 6n + 1 with n as an integer then the check is stopped there and the number is returned as not being prime, if it does meet that criteria then the Fermat primality check is performed. After the prime check is performed the outcome is returned (whether prime is True or False).

    while (count < 10):
             count = count + 1
            while gcd(a, num) != 1:                a = a + 1        if pow(a, num - 1, num) != 1:                count = 10                prime = False        a = a + 1
    The check is performed 10 times with a different value of a to ensure that the number is not a Poulet prime, that is why there is a loop while count is less than 10. The loop starts by making a note that the check has been performed by increasing count by 1, a check is then performed to ensure that a and num are coprime, if they are not a is changed and the check is reperformed. Once a and num are coprime we utilise the pow function, pow(a,b,c) returns the remainder of ab/c; so in this code we are utilising this function to utilise Fermat's little theorem to check that num is prime by finding the remainder of anum - 1/num and if this is not 1 then the test has failed and num is immediately returned as false. If all the checks come back with no problems then num is returned as prime.

    This is it for the coding of the actual prime checker, the rest of the programming is to give the program structure, variables and how to save the outcome of each check.
    num = input("First prime to check ")
    lastnum = input("Last prime to check ")
    while num <= lastnum:
            prime = primecheck(num)
            if prime == True:
                    FILE = open("primes.txt", "a")
                    FILE.write(str(num))
                    FILE.write(", ")
                    FILE.close()
                    print num," is prime."
            else:
                    print num, " is not prime."
            num = num + 2
    To begin two variables are created for the first prime number to check and the last prime number to check in order to give the program an end point. While the number to be checked is less than the last number a check will be performed. A boolean variable prime is assigned to the output of the primecheck when performed on num. If prime is true then a text document called primes is opened to append and the number is added to it, read more on editing files from within Python. A message is displayed to the user to state whether the number is or is not prime. 2 is added to the previous number to ensure that the next number is odd, this relies on the fact that the first number entered was also odd, if it was not then you would be checking whether or not only even numbers are prime which obviously they will not be (except 2).

    And that is it for the whole program! Hopefully yours is now working correctly, if you have any problems please leave a comment and I will help you as soon as I can. If you haven't already you may wish to download my .exe prime checkerdownload my source code or you may want to download my list of the first 7,000,000 prime numbers created with this prime checker.

    Monday, 27 August 2012

    Highest Common Factor: Proving Euclid's Algorithm

    The Euclidean algorithm will find the highest common factor of two numbers (the largest number that will divide both numbers). It is a rather simple algorithm to understand and implement having been discovered by the great mathematician Euclid of Alexandria 300 BC making it one of the oldest algorithms still applicable and in use in modern times.

    Overview of Euclidean Algorithm


    1.) Begin by inputting two numbers m and n
    2.) If m < n then swap m and n (the larger number should be set to m)
    3.) Divide m by n then get the remainder from this, r. If r = 0 then return n as the highest common factor and stop the algorithm.
    4.) Let m = n and n = r. Repeat step 3.

    The obvious questions here are "why does this work?" and "how do you know that the answer is always correct?". The best way to answer these questions is through an example.

    Example: Find the highest common factor of 216 and 38.
    From the algorithm we must set m = 216 and n = 38, m/n gives a remainder of 26. We now set m = 38 and n = 26, m/n gives a remainder of 12. Set m = 26 and n = 12, m/n gives a remainder of 2. Set m = 12 and n = 2, m/n gives a remainder of 0 so the highest common factor of 216 and 38 is 2.

    It is clear from this algorithm that the important element from one step to the next relies on the fact that hcf(m,n) = hcf(n,r) is true. We will write this as a lemma.


    This is how the algorithm works but it is not a proof as to that it will always work on any two integers, m and n. To prove this we will utilise how the algorithm in a more formal sense and then utilise those facts to prove the algorithm is consistent and thus correct.


    And that is how and why the Euclidean algorithm works! It is relatively simple to program this algorithm and because of this and that it is very efficient it has many uses in mathematical programs, most importantly (to me!) is for prime checkers.

    Saturday, 28 January 2012

    How to Program the mth Root Algorithm

    If you have read my post on how to find the mth root of a number, you will see that the algorithm converges painfully slowly as m begins to increase the series converges painfully slowly and it is not at all practical to do by hand, so you may be wondering what the point of the algorithm really is at all. Well calculators need an algorithm on how actually to compute the "mth root" of a number, and this is how.

    To start with I will note that I am using Visual Basic 2008 to program this, but it shouldn't be too hard to alter the code to the appropriate language as Visual Basic is very similar to pseudocode so it is easy to read. It should also be noted that the original algorithm I devised is so inefficient for larger values of m that even with 1,000,000,000 iterations, it can still be wildly out; the newer, more efficient algorithm is very similar to the older one, as you will see.


    Now that the ground work is out of the way it is just the simple matter of translating this into a program. Start by creating two labels (names do not matter as they will not be used in the code), two text boxes (txtNumber and txtRoot) and a button (btnRoot).


    Now go into your code and create a function called mth_root with inputs of number and root. The code for this function will be:


    You begin the function by declaring the local variables index and calc_use, index is used solely as a loop counter and calc_use is a variable that will change constantly whilst the loop is ongoing, the initial value of calc_use can be anything (except 0), the series converges well so a low starting point is fine. The key part of the function is the loop ("For... Next") as this is where the calculation is done again and again. You may notice that it is done 1,000,001 times and this is not a necessity and it should be just as accurate if repeated a small fraction of this. The Return calc_use ensures that the last result from the loop is kept in the memory.

    We now have the function to be used, but it is not being used yet, so we need to have the function to be ran on an event, the event we will use is the click of a button.


    The first line of the code is only there to say that this code is to be executed on the click of a button and this can be replicated b double clicking your button on your form. We start again by declaring the variables we will use in this code snippet. We declare the number as the text entered into the txtNumber text box, the root variable is declared as the text entered into the txtRoot text box and the answer variable utilises the function we have created with the user defined variables.

    The result of this function is output in a message box including a message as to what the number was and what the root was. You may notice that if you wanted the square root the box would say "The 2th root of...", and this too bugs me, a lot. But for the purposes of keeping this tutorial less complicated I didn't want a long If statement to simply change the suffix of the root.

    If you have copied what I have done exactly it should be functioning perfectly and you can test it yourself. 


    You can check this answer on your calculator, but it is in fact correct (note it is also correct if we set it to loop just from 0 to 100).

    If you do not want to type the code out you can view my source code, feel free to experiment with it, try to utilise it in a calculator you create or anything else you desire. If you would just like to test out the program you can download it and see it in all its brilliance. Note, it may not actually be brilliant. Use at your own discretion.

    Saturday, 19 March 2011

    An introduction to Python

    Now, I am by no means adept at python; far from it in fact. I have attempted to learn many programming languages several times, all end within a couple of days and finish up with me not wanting to touch another programming language again. But I got to thinking, I need to regularly update my blog and need ideas on what to do each post on. So I thought, I will update as a go along with mini lessons that should hopefully inspire and help people who are first beginning to code in Python.

    Why Python first of all? Well, it is one of the simpler first languages to learn that is actually used by large corporations (one of the most notable are Walt Disney). It isn't exactly too complex to begin with and has a steady difficulty curve. And an added bonus? It's very mathematical!

    The first thing you need to do really is download Python. The current version (as of 19th March 2011) is 3.2, but the majority of what I will discuss is from the 2.x versions, however they are not too different and the 3.x versions is basically just cleaned up from 2.x versions. However 2.x has a far greater library support, meaning custom variables that other people have created are much more readily available.

    Download Python here. Another download that you may want is Notepad++ the amount of languages it recognises is pretty phenomenal; from HTML to Python and everything in between. If you'd like this brilliant open source software go here.

    Once you've downloaded all of these we'll start you off with your first lesson. I will begin by introducing probably the most important command in Python, it's incredibly simple but is used to display any text.

    "Hello world!" is the absolute must as it goes for starter programs, so that's what we'll do.
    print "Hello world!"
    When the program is ran it shows:
    Hello world! 
     And that's it. Things to take note of are; the print command and the quotes. Any string of text has to have quotes surrounding it, else it does not make sense. And the print command has to come before any text you want to be "printed". And that's it for now, but the next lesson will be far more technical.