1 Replies - 1992 Views - Last Post: 16 November 2013 - 08:14 AM

#1 erik.price   User is offline

  • D.I.C Lover
  • member icon

Reputation: 486
  • View blog
  • Posts: 2,690
  • Joined: 18-December 08

Collatz Conjecture (3n+1 Problem)

Posted 28 November 2009 - 12:30 PM

Description: Recursively solves the Collatz conjecture (divide by 2 if even, multiply by 3 and add 1 if odd) until it converges at 1
def collatz(n)
	print "#{n} "
	if n > 1
		if n % 2 != 0
			collatz(3*n + 1)
		else
			collatz(n/2)
		end
	end
end


#Example
collatz(21) #=> 21 64 32 16 8 4 2 1 


Is This A Good Question/Topic? 0
  • +

Replies To: Collatz Conjecture (3n+1 Problem)

#2 Lemur   User is offline

  • Pragmatism over Dogma
  • member icon


Reputation: 1453
  • View blog
  • Posts: 3,633
  • Joined: 28-November 09

Re: Collatz Conjecture (3n+1 Problem)

Posted 16 November 2013 - 08:14 AM

def collatz(n); print "#{n} "; n > 1 ? ( n % 2 == 0 ? collatz(3 * n + 1) : collatz(n / 2)) : 1; end
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1