Joseph Jude

Technology, Psychology, and Story Telling

Largest palindrome made from the product of two 3-digit numbers

Posted: Tags: code,euler,swift,tsc,python

What I learnt (WIL):

  • Swift is pathetically slow in double for loop (even in compiled form)
  • Syntaxes keep changing (.reverse() is .reversed() in v3); So you waste time searching
  • String reversal is so simple and easy in python compared to typescript & swift

Python

answer = 0
for i in xrange(999, 100, -1):
  for j in xrange(i, 100, -1):
    k = i * j
    s = str(k)
    if s == s[::-1] and k > answer:      
      answer = k

print answer

Typescript

var answer = 0
var k = 0

for (var i = 100; i < 1000; i++) {
  for (var j = 100; j < i; j++) {
    k = i * j
    var kstr = k.toString()
    var reversed = kstr.split("").reverse().join("")
    if ((reversed == kstr) && (k > answer)) {
      answer = k
    }
  }
}

console.log(answer)

Swift

var answer = 0
var k = 0
var s = ""

var i = 100
var j = 100

while i < 1000 {
  while j < i {
    k = i * j
    s = String(k)
    if s == String(s.characters.reverse()) && k > answer {
      answer = k
    }
    j += 1
  }
  i += 1
  j = 100
}

print(answer)
//906609

Git Repository / All Euler Solutions

Got comments? Tweet it, or comment below.



Like the post? Retweet it. Got comments? Reply.

Comments

comments powered by Disqus