Category Archive: Code

Euler 9

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a
2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.

There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
Link to Problem 9

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def f(x):
    # Given: a²+b²=c² and a+b+c=1000
    # then: c=1000-a-b :.
    # a²+b²=(1000-a-b)² :.
    # a²+b²=1000000-1000a-1000b-1000a-a²+ab-1000b+ab+b² :.
    # 0=1000000-2000a-2000b+2ab :.
    # a=(1000000-2000b)/(2000-2b)
    return (1000000.0-2000.0*x)/(2000.0-2.0*x)
 
a=0
b=1.1
while b != int(b):
    a+=1
    b=f(a)
 
c=(a**2+b**2)**.5
 
print a*b*c

Euler 14

The following iterative sequence is defined for the set of positive integers:

n → n/2 (n is even)
n → 3n + 1 (n is odd)

Using the rule above and starting with 13, we generate the following sequence:

13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
Link to Problem 14

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# To do this efficiently we use a dictionary to remember how many steps it takes to get to
# 1 from any other number. This allows us to use a recursive function, but never perform
# the same calculation twice
 
def sequence(x):
    def f(x):
        if x==1: return 0
        if x%2==0:
            return sequence(x/2)+1
        else:
            return sequence(3*x+1)+1
    try:
        if x in sequence.d:
            return sequence.d[x]
    except:
        sequence.d = {}
    sequence.d[x] = f(x)
    return sequence.d[x]
 
large=0 # track the largest value
ans=0 # track the answer corresponding to the largest value
for i in range(1,1000000):
    temp=sequence(i)
    if temp>large:
        large,ans = temp, i
 
print ans

Euler 21

Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.

For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.

Evaluate the sum of all the amicable numbers under 10000.
Link to Problem 21

def sum_of_div(x): # sum of all divisors of x
  def f(x):
    sum=1
    for i in range(2,int(x**.5)):
      if (x%i == 0):
        sum += i + x/i
    if int(x**.5) == x**.5:
      sum += x**.5
    return sum
  try:
    if x in sum_of_div.d:
      return sum_of_div.d[x]
  except:
    sum_of_div.d = {}
  sum_of_div.d[x] = f(x)
  return sum_of_div.d[x]

def is_amicable(x): # return true if x is amicable
    a=sum_of_div(x)
    b=sum_of_div(a)
    return b==x and a!=x

def sumOfAmicablePairs(x):
  sum=0
  for i in range(1,x):
    if is_amicable(i):
      sum+=i
  return sum

print sumOfAmicablePairs(10000)

Memory Game

This JavaScript game will display a block of numbers for a few seconds. Then you have to try and remember the order the numbers were in. Play this every day for a few weeks and you will really feel yourself improving. I hope to program several more games like this and wrap them together, but we’ll see if that happens. The code for this is entirely in JavaScript, so take a look at the source code.

Memory Game

Mandlebrot

This program is a complete abuse of HTML, CSS and JavaScript. Put bluntly, it is a bad idea and a disgrace to all programmers that I even tried to code it. That said it’s really cool. Explore Mandlebrot and Juilasets from your browser using JavaScript. Start small and if you have firebug, turn it off first. Really if you set this too big you will crash your browser. I’ve included links to set a few points that I find interesting.

Mandlebrot/Julia Explorer

Particle Effects

This demonstrates three simple particle effects using JavaScript and a canvas element. The green particles follow an attractor style pattern when the particle accelerates towards the point of interest, in this case the mouse. The blue particles are radiant. They start from the point of the interest and moves outward and a random speed and direction. The red particles are a sort of spark pattern. It starts out like blue, moving in a random speed and direction but has gravity applied so that it seems to fall.

Initially I was working on a complex formula for when to respawn a particle, but after some experimentation I found that giving it a random 5% chance to respawn every time it is refreshed worked really well (and is simple the code). On top of that there is 0.25% chance that the particle will disappear entirely. This can be switched off by deactivating decay. You can also turn different particles on and off. This demo uses canvas and will not work in IE at this time. Click on the white area to spawn particles. Warning, this can run very slow on some computers.

Particle Effects

Private Variables

Douglas Crockford demonstrated this method for programming Private variables in JavaScript. My demo is not flashy but it gets the point across. Be sure to take a look at the source code to see what’s going on.

One of the shortcomings of this technique is that it cannot be coupled with prototypes. It is not possible (as far as I’m aware) to have a prototype with private variables.

Private Variable Demo

Math Quiz and Flash Cards

This program creates simple flash cards for memorizing math problems. Options include which operators to use, how long to show the cards for and the number range to use. A good example of using JavaScript to manipulate the DOM.

Math Flash Cards

This program is the follow up to the flash cards program. Similar interface and options but takes user input and tracks score. After the quiz is completed a score is given. Another good JavaScript example for DOM manipulation, largely taken from the flash cards example.

Math Quiz

Binary Tree Sorter

This program is an implementation of a binary tree in JavaScript. Binary trees are a basic computer science data structure. Learn more about binary trees here. The code provides a good model of a simple binary tree if you are just learning to write code.

Javascript Binary Tree

Mastermind

This is a game I used to play a lot when I was younger. Try to guess a hidden pattern of colors. After each guess you will receive feedback tell you how many colors are correct and how many are in the right spot. The interface is pretty simple and it’s kind of fun. This program is also special to me because it was one of my first JavaScript projects. I have cleaned up the code over the years as I’ve learned more about JavaScript.

Mastermind Game

Older posts «

» Newer posts