Oct 3, 2009

Sum from 1 to 10 without loop

Can you sum from 1 to 10 without loop? It's a programming quiz which is in now in Japan.

You may solve it with inject method in Ruby.


puts (1..10).inject(:+)


Is it not interesting? Then, I write it with continuation.


n, s = callcc {|$c| [1, 0] }
n, s = $c.call [n.succ, n + s] if n <= 10
puts s


Additionally, you can use recursion without loop.

No comments: