Thursday, 14 July 2011

Problem 14

Python solution

<pre class="brush: python">

n = 2

maxm = 1

while n < 1000000:

    k = n

    cnt = 0

    while k != 1:

        if k%2 == 0:

            k = k/2

        else:

            k = 3*k + 1

        cnt = cnt + 1

    if cnt > maxm:

        maxm = cnt

        num = n

    n = n + 1

    if n%100000 == 0:

        print n,

print num

</pre>

Tuesday, 28 June 2011

Problem 2

For project Euler problem - 2  one python solution is given here:
https://github.com/sanand0/euler/blob/master/002.py

The meaning of dict.get is given here:
http://www.java2s.com/Code/Python/Dictionary/Dictionarygetvalue.htm

Consider the statement
cache[n] = cache.get(n, 0) or (n <= 1 and 1 or fib(n-1) + fib(n-2))

or AND and operators are short circuited.
If n <= 1, "n <= 1 and 1" evaluates to True.
so cache[-1],cache[0],cache[-2] evaluates to True.




Problem - 1

For project Euler problem -1 one python solution is given here:
http://www.s-anand.net/euler.html
The meaning of the statement "if not i % 5 or not i % 3" is "if i divides 3 or 5 or both then n = n + 1".
If i%j == 0 is true then "not  (i%j)" evaluates to True.