Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

/prog/ Challenge

Name: Anonymous 2007-09-04 15:06 ID:bG0CVxDp

Hey, I've stolen this challenge from some website, it's pretty easy but I know most of you will fuck it up.

A sequence is defined by:

n -> n/2 (n is even)
n -> 3n + 1 (n is odd)

Find the longest sequence, with a starting number under one million.

Bonus points when you find the solution for ten million.

Name: Anonymous 2007-09-05 9:39 ID:Heaven

Someone write a Ruby version so that we can confirm that Ruby indeed is slow as fuck.

Name: Anonymous 2007-09-05 10:26 ID:N3V2WcCD

>>43

Average run time is 162.9 seconds (running on same PC as Python and Java measurements from earlier)

Am I doing it wrong, or is Ruby indeed slow as fuck?

This is the first Ruby program I've ever written, so maybe I'm missing some fundamentals.

Code below:

def sequencelength(n)
  if n == 1 or n == 2 or n == 4
    len = 3
  else
    len = 1
    while n > 1
      if n%2 == 0
        n = n/2
      else
        n = 3*n + 1
      end
      len = len + 1
    end
  end
  return len
end

longestseqlen = 0

starttime = Time.now()

for n in 1..1000000
  curseqlen = sequencelength(n)
  if curseqlen > longestseqlen
    longestseqlen = curseqlen
  end
end

print "longest sequence is ",longestseqlen,"\n"
print "run time is ",Time.now()-starttime,"s\n"

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List