Wednesday, August 21, 2013

Euler #1 and #2

This is a simple solution to the first Euler problem
http://projecteuler.net/problem=1


import sys
import time
sum=0
for a in range (3,10):
    if ((a%3==0) or (a%5==0)):
        sum+=a



This is a simple script that should be simple to understand.
import is python's means of accessing functions in external files.

The for loop structure in python is a bit different compared to Basic or C/Java. Range(0,n) makes a list of numbers from 0 to n-1. i.e. n is not included.
For a in <list> will iterate through the list, and the variable "a" will represent each element in that iteration.

Here's my solution to Euler 2:
http://projecteuler.net/problem=2



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

num1=1
num2=2
sum=0

while num1<4000000:
    if (not num1%2) and num1 < 4000000:
        sum+=num1
    if (not num2%2) and num2 < 4000000:
        sum+=num2
    num1+=num2
    num2+=num1
print sum


This is another fairly basic algorithm. No need to worry about memory and fairly simple checks. Fibonacci explodes fairly quickly so the number of iterations here is low - under 20.

That's all for now. Both quite simple. Problem 3 gets much more interesting.

No comments:

Post a Comment