I have a dream that one day, students in maths and computer science from all over the world will unite to solve the greatest mathematical problems of all times.
Indeed, this day has almost come. ProjectEuler.net is a great learning tool which focuses on solving maths problems with the aid of some programming. The choice of the language and the method is left to the participant, only the answer is recorded. However, methods used are discussed in a specific thread for each problem (there are more than 160 problems).
I started using C++ but quickly noticed how simpler and shorter the ruby solutions were. So I went with Ruby and it went very smoothly even through I didn’t know the API.
I’m surprised at how many people keep submitting solutions using assembler language, I hope it’s just for the fun of showing their insanity. 😉
Here are some of my ruby solutions (warning spoiler ahead):
ex4: Find the largest palindrome made from the product of two 3-digit numbers.
# x, y 3-digits # z=x*y # 100*100 < z < 999*999 def isPalindrom(n) if (n.to_s==n.to_s.reverse()) return true else return false end end def f() max=0 for x in 100..999 for y in 100..999 z=x*y if isPalindrom(z) #puts z if (z>max) max=z end end end end return max end puts f()
ex6: Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
def diff(n) return n*n*(n+1)*(n+1)/4-n*(n+1)*(2*n+1)/6 end puts diff(ARGV.to_i)
ex7: What is the 10001st prime number?
require 'mathn' f = 0 primes = Prime.new for i in 1..10001 f = primes.next end puts f
ex9: There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
def f(n) for a in 1..n for b in a+1..n for c in b+1..n if (a*a+b*b==c*c) if (a+b+c==1000) return a*b*c end end end end end return 1 end puts f(ARGV.to_i)
I now have completed more than 16 problems. The difficulty increases gradually. On problems 12 and 15, my first scripts were too long to execute (more than 1 week), as I expected, I add to rewrite my beautiful bi-recursive function to something much more iterative. The results were astonishingly better, in less than one second, I had accomplished much more calculations than in one week with the previous method.