Sum of all the primes below two million

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

Seemed pretty straight forward, loop through all numbers up to 2,000,000 – if they’re prime add them to a tally.

Module Module1

  Sub Main()
    Dim beganAt As Date = Now
    Dim n As Integer = 2000000
    Dim total As Long = 0

    For counter As Integer = 2 To n
      If isPrime(counter) = True Then
        total = total + counter
      End If
    Next

    Dim endAt As Global.System.TimeSpan = Now.Subtract(beganAt)
    Dim took As Integer = endAt.Milliseconds

    Console.WriteLine(total.ToString + " in " + took.ToString + " ms.")
    Console.ReadKey()
  End Sub

  Private Function isPrime(ByVal thisNumber As Integer) As Boolean
    ' Prime numbers other than two are odd...
    If thisNumber = 2 Then
      Return True
    ElseIf thisNumber Mod 2 = 0 Then
      Return False
    End If

    'Check it isn't divisible by up to its square root
    '(consider n=(root n)(root n) as factors)
    For counter As Integer = 3 To (Math.Sqrt(thisNumber)) Step 2
      If thisNumber Mod counter = 0 Then
        Return False
      End If
    Next
    Return True
  End Function

End Module

Just needed to be careful with data types – VB.Net’s Integer isn’t large enough so I changed to a Long. Gives 142,913,828,922 in 953 milliseconds.

 

 

Posted in Coding | Tagged , , | 2 Comments

Pythagorean triplet

Project Euler again, this time its problem 9.

A Pythagorean triplet is a set of three natural numbers, a<b<c, for which:

a^{2}+b^{2}=c^{2}

For example:

3^{2}+4^{2}=9+16=25=5^{2}.

There exists exactly one Pythagorean triplet for which abc = 1000.
Find the product abc.

My first draft is simply brute force checking:

Module Module1

  Sub Main()
    Dim beganAt As Date = Now

    Dim answer As Integer = pythagorean(1000)

    Dim endAt As Global.System.TimeSpan = Now.Subtract(beganAt)
    Dim took As Integer = endAt.Milliseconds

    Console.WriteLine(answer.ToString + " in " + took.ToString + "ms.")
    Console.ReadKey()
  End Sub

  Private Function pythagorean(ByVal thisNumber As Integer) As Integer
    For a As Integer = 1 To thisNumber
      For b As Integer = 1 To thisNumber
        For c As Integer = 1 To thisNumber
          If a + b + c = 1000 Then
            If (a * a) + (b * b) = (c * c) Then
              Return (a * b * c)
            End If
          End If
        Next
      Next
    Next
    Return -1
  End Function

End Module

It takes 375 milliseconds but gives the correct answer.

 

Posted in Coding | Tagged , , , | Leave a comment

The 10001st prime number

Project Euler time again, I’ve come out of sequence – here’s problem 7:

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10001st prime number?

I’m going to start at the beginning and check if each is a prime, until I find the 10001th.

Module Module1
  Sub Main()
    Dim beganAt As Date = Now
    Dim n = 10001
    Dim prime As Integer = 0
    Dim counter As Integer = 0

    ' Check each number until you've got 10001 prime numbers.
    Do Until prime = n + 1
      counter = counter + 1
      If isPrime(counter) Then
        prime = prime + 1
      End If
    Loop

    Dim endAt As Global.System.TimeSpan = Now.Subtract(beganAt)
    Dim took As Integer = endAt.Milliseconds

    Console.WriteLine(counter.ToString + " in " + took.ToString + "ms.")
    Console.ReadKey()
  End Sub

  Private Function isPrime(ByVal thisNumber As Integer) As Boolean
    ' Prime numbers other than two are odd...
    If thisNumber = 2 Then
      Return True
    ElseIf thisNumber Mod 2 = 0 Then
      Return False
    End If

    'Check it isn't divisible by up to its square root
    '(consider n=(root n)(root n) as factors)
    For counter As Integer = 3 To (Math.Sqrt(thisNumber)) Step 2
      If thisNumber Mod counter = 0 Then
        Return False
      End If
    Next
    Return True
  End Function

End Module

I used a function for finding primes, it keeps coming up. It takes an integer and returns true or false by discounting even numbers except 2 and checking for divisibility up to the integer’s square root. If you consider n=\sqrt{n}\times\sqrt{n} then if you have not found a number that divides into n evenly once reaching \sqrt{n}, its factors can only be one and itself. This significantly reduces processing time and appears to be how my HP40gs works out its ISPRIME() function.

It gives the answer 104743 in 125 milliseconds.

Posted in Coding | Tagged , , , | Leave a comment

Running injuries

My Dailymile report is looking a little sorry for itself this week as I’ve picked up an injury. Tendinitis – doctor recommends two weeks off running, anti-inflammatories, ice and rest. He suggested investigating my running shoes too, so I went in to my local running shop.

Starting with a set of neutral trainers, you run on a treadmill, which has a little video camera behind it. You can analyse your gait and adjust accordingly. Five pairs of trainers later and it appears that I need a moderate stability shoe as I over-pronate. Its also clear I need to focus on my running style because I seem to turn out my right foot a lot.

I thought I was going to get caught on the price but a pair of Asics GT2160 were quite reasonable and if it makes the difference its worth it. They offered a 30 day guarantee too, so I can go back if they make no difference.

Posted in Running | Tagged | Leave a comment

Largest prime factor of a composite number

The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?

Prime factors are prime numbers that can be multiplied together to make a given number. One way to find them is to start by dividing the number by the first prime (2) and continuing to do so until it cannot be divided, then moving on to the next.

Module Module1
  Sub Main()
    Dim beganAt As Date = Now
    Dim n As Long = 600851475143
    Dim factor As Integer = 2
    Dim highestFactor As Integer = 1
    While n > 1
      If n Mod factor = 0 Then
        highestFactor = factor
        n = n / factor
        While n Mod factor = 0
          n = n / factor
        End While
      End If
      factor = factor + 1
    End While
    Dim endAt As Global.System.TimeSpan = Now.Subtract(beganAt)
    Dim took As Integer = endAt.Milliseconds
    Console.WriteLine(highestFactor.ToString + " in " + took.ToString + "ms.")
    Console.ReadKey()
  End Sub
End Module
Posted in Coding, Computing, Open University | Tagged , , , | Leave a comment

Sum of all even Fibonacci terms below 4 million

The second Euler problem concerns the Fibonacci sequence, which for anyone doing MS221 is the basis of module A1.

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Following the logic from the previous problem, then I can check each number of the Fibonacci sequence to see if it’s even and add it to the total, n_{3} = n_{2} + n_{1} where n_{0}=1. We need to repeat this while n < 4000000 and add n to our total if it’s even.

Sub Main()
    Dim beganAt As Date = Now
    Dim n, n1, n2, total As Integer
    n1 = 0
    n2 = 1
    Do While n2 < 4000000
        n = n1 + n2
        n1 = n2
        n2 = n
        If n < 4000000 Then
            If n Mod 2 = 0 Then
                total = total + n
            End If
        End If
    Loop
    Dim endAt As Global.System.TimeSpan = Now.Subtract(beganAt)
    Dim took As Integer = endAt.Milliseconds
    Console.WriteLine(total.ToString + " in " + took.ToString + "ms.")
    Console.ReadKey()
End Sub

Gives an answer of 4613732, which is correct. I know there is a more efficient approach but I’m tired and pissed off. Today was not a good day.

 

 

Posted in Coding | Tagged , , | Leave a comment

Find the sum of all the multiples of 3 or 5 below 1000

Project Euler’s first problem:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

By brute force I can write code that checks every number below 1000 to see if it’s divisible by 3 or 5, if it is then add it to a running total.

I’m using Visual Basic (VB.Net 2010 to be precise). This might seem a little odd for an Ubuntu member but I’m thinking of trying MT264 (Designing applications with Visual Basic). Open University students qualify for Microsoft’s Dreamspark promotion, so I got a copy of Visual Studio 2010 Express to try it out. Besides, I’m at work so haven’t much choice.

Starting off with a “Console Application” template:

Dim beganAt As Date = Now
Dim total As Long = 0
' Repeat a thousand times
For counter As Integer = 1 To 999 Step 1
     ' Check if the current integer is divisible by 3 or 5 and
     ' if it is then add it to our total
     If (counter Mod 3 = 0) Or (counter Mod 5 = 0) Then
          total = total + counter
     End If
Next
Dim endAt As Global.System.TimeSpan = Now.Subtract(beganAt)
Dim took As Integer = endAt.Milliseconds
Console.WriteLine(total.ToString + " in " + took.ToString + "ms.")
Console.ReadKey()

Running this code and clicking the button we get the answer 233168, which Project Eular confirms. Code must run in less than a minute, the timer shows less than a millisecond.

I can see another way to do this, by using two for loops – one in steps of 3 and one in steps of 5, adding the counter to a total for each. I don’t know if this offers a significant time saving, so I re-ran the original code, making the loop repeat a million times and it completes in 375ms. I can’t see any value in going any further.

Posted in Coding | Tagged , , , | 1 Comment

Finally succeeding?

I read an article by James Somers at The Atlantic called “How I Failed, Failed, and Finally Succeeded at Learning How to Code“. I’d encourage anyone with an interest in learning to code to read it – he discusses how computer programming is an excellent learning experience but that his own experiences have been tempered by poor instruction, particularly from books. He goes on to discuss how Project Euler became the titular success.

Euler provides a series of programming challenges of increasing difficulty, as the student solves each in turn they gain experience of what does and does not work as well as confidence in their abilities. Importantly, the student is also applying programming to practical problems (if you’re a mathematics student) from the outset.

I’ll post my solutions here as I go. I’m aiming to do one a day but I’ll see how I get on. Not sure what language is best to get on with, Python is popular in open source circles but most of my courses are based around Java.

 

Posted in Coding, Computing, Open University | Tagged , , , | Leave a comment

Completing BSc (Honours) Computing and IT

With ten years remaining in my contract and the government’s intentions unclear, I’ve decided to get my finger out and focus on completing the BSc (Honours) Computing and IT (B62). It can use 120 points from four completed modules - M150T175MST121 and M255 as well as 30 points from MS221, which I have already started.

At level two I’m taking two courses on top of MS221 which I intend to study concurrently, so as to be half way through by the end of next year:

  • T215 - Communication and information technologies (60)
  • MT264 - Designing applications with Visual Basic (30)

Leaving 120 points at level 3:

  • M359 - Relational databases: theory and practice (30)
  • M364 – Fundamentals of interaction design (30)
  • M366 – Natural and artificial intelligence (30)
  • TM470 – The computing and IT project (30)
Posted in Computing, Open University | Tagged , , , , , , | Leave a comment

Running

Since I got back at the end of May I’ve been running further, increasing to around 22 miles a week.

Annoyingly, I’ve picked up what I suspect is Tendinitis although I’m not sure which of the tendons it is in my left foot. I’ll make a doctors appointment tomorrow – assuming I see someone this week, they’ll no doubt prescribe Ibuprofen and shunt me to physiotherapy.

I’ve kept running but reduced the distance, started doing specific stretches and using cold packs to reduce any pain. I’m going to re-lace my shoes and see if it makes a difference.

Posted in Running | Tagged | Leave a comment