Commits

Lars Yencken committed 5b62fbd

Julia 01-05.

Comments (0)

Files changed (5)

julia/01-sum-numbers.jl

+#!/usr/bin/env julia
+#
+#  01-sum-numbers.jl
+#  euler
+#
+
+s = 0
+for i = 1:999
+    if i % 3 == 0 || i % 5 == 0
+        s += i
+    end
+end
+
+println(s)

julia/02-sum-fibonacci.jl

+#!/usr/bin/env julia
+#
+#  02-sum-fibonacci.jl
+#  euler
+#
+#  Sum all even elements of the fibonacci sequence whose values are less than
+#  4 million.
+#
+
+function fib(lim)
+    xs = Int[]
+    push!(xs, 1)
+    push!(xs, 2)
+    i = 2
+    x = xs[i] + xs[i - 1]
+    while x < lim
+        push!(xs, x)
+        i += 1
+        x = xs[i] + xs[i - 1]
+    end
+    sum(xs[mod(xs, 2) .== 0])
+end
+
+println(fib(4000000))

julia/03-prime-factors.jl

+#!/usr/bin/env julia
+#
+#  03-prime-factors.jl
+#  euler
+#
+
+"""
+Calculate the largest prime fator of 600851475143.
+"""
+
+function factorize(x)
+    factors = Set{Int64}()
+
+    while x > 1
+        for i = 2:x + 1
+            if x % i == 0
+                add!(factors, i)
+                x = div(x, i)
+                break
+            end
+        end
+    end
+
+    factors
+end
+
+println(max(factorize(600851475143)))

julia/04-palindrome.jl

+#!/usr/bin/env julia
+#
+#  04-palindrome.jl
+#  euler
+#
+
+"""
+Find the largest palindrome made from the product of two 3-digit numbers.
+"""
+
+function ispalindrome(x)
+    s = string(x)
+    for i = 1:div(length(s), 2)
+        if s[i] != s[end + 1 - i]
+            return false
+        end
+    end
+    return true
+end
+
+h = 1
+for i = 100:999
+    for j = 100:999
+        if ispalindrome(i * j)
+            h = max(h, i * j)
+        end
+    end
+end
+
+println(h)

julia/05-divisible.jl

+#!/usr/bin/env julia
+#
+#  05-divisible.jl
+#  euler
+#
+#  2520 is the smallest number that can be divided by each of the numbers
+#  from 1 to 10 without any remainder. What is the smallest positive number
+#  that is evenly divisible by all of the numbers from 1 to 20?
+#
+
+function factorize(x)
+    factors = Dict{Int64,Int64}()
+
+    while x > 1
+        for i = 2:x + 1
+            if x % i == 0
+                factors[i] = get(factors, i, 0) + 1
+                x = div(x, i)
+                break
+            end
+        end
+    end
+
+    factors
+end
+
+shared_factors = Dict{Int64,Int64}()
+for i in 2:20
+    factors = factorize(i)
+    for (j, n) in collect(factors)
+        shared_factors[j] = max(get(shared_factors, j, 0), n)
+    end
+end
+
+println(reduce(*, [n^k for (n, k ) in collect(shared_factors)]))