Saturday, September 28, 2013

Project Euler Answer Codes 1-5


Solutions for problems at http://projecteuler.net/problems written using the online compiler http://py-ide-online.appspot.com/

# Problem 1   :

Multiples of 3 and 5

tot5 = 0
x = 0
print "start"
print "fives"
while x <= 1000:
  tot5= tot5 + x
  print x
  x=x+5
x=0
print "threes"
while x <= 1000:
    if x % 5 <> 0:
        tot5=tot5+x
        print x
    x= x+3   
print tot5

# Problem 2 

Even Fibonacci numbers

tot5 = 0
x = 0
y = 1
temp = 0
temp1 = 0
print "start"
while y < 4000000:
  if y % 2 == 0:
    tot5= tot5 + y
  temp = y
  temp1 = x
  x = y
  y = temp1 + temp
print tot5

# Problem 3

Largest prime factor

I think i found the shortest way to do that. Written in Matlab
target = 600851475143;
f = factor(target);
max(f)

# Problem 4

Largest palindrome product

My solution in matlab. One of the slowest method but also one of the most basic method to understand and implement. Most cpu time is spent on the num2str function though. Not my fault. Took 50 seconds to process.

a = 999;
b = 999;
pal = 0;
max = 0;
while a > 100
    found = 0;
    b = 999;
    while (b > 100) && (found == 0)
        inta = a * b;
        stra = int2str(inta);
      if (fliplr(stra) == stra)
         found  = 1;
      end
      b = b -1;
    end
    if pal > max
        max = inta
        a
        b
    end
    a = a - 1;
end 

# Problem 5

Smallest multiple

No programming solution went like this 19 * 18 * 17 * 16 * 15 * 14 * 13 * 11 and the rest would be divisible since the rest are already multiples of these. now 18, 16, 15, 14 are not prime numbers so they are adding multiples useless to the product. We need to remove these multiples. There's 3 hanging in both 18 and 15, remove them/ likewise we have a 2 hanging in 14 and 18. remove them. multiply by the 3 and 2 you removed. 19*3*17*4*5*7*13*11*3*2 Now we cant't remove anything else without loosing our higher multiples.
436 problems to go

No comments:

Post a Comment