Why does mathn kill this method?

S

Siep Korteling

Really stumped here.

def sum_digits(n)
sum = 0
while n>0
sum += n % 10
n /= 10
end
sum
end

STDOUT.sync=true

puts sum_digits(12) #=> 3

require 'mathn'
puts sum_digits(12) # hangs


What am I doing wrong?
 
C

Christopher Dicely

Really stumped here.

def sum_digits(n)
=C2=A0 =C2=A0sum =3D 0
=C2=A0 =C2=A0while n>0
=C2=A0 =C2=A0 =C2=A0 sum +=3D n % 10
=C2=A0 =C2=A0 =C2=A0 n /=3D 10
=C2=A0 =C2=A0 =C2=A0 end
=C2=A0 =C2=A0sum
=C2=A0end

STDOUT.sync=3Dtrue

puts sum_digits(12) #=3D> 3

require 'mathn'
puts sum_digits(12) # hangs


What am I doing wrong?

This should illustrate the problem:

irb(main):001:0> require 'mathn'
=3D> true
irb(main):002:0> n =3D 10
=3D> 10
irb(main):003:0> n /=3D 10
=3D> 1
irb(main):004:0> n /=3D 10
=3D> 1/10
irb(main):005:0> n /=3D 10
=3D> 1/100

The solution:

def sum_digits(n)
sum =3D 0
while n>0
sum +=3D n % 10
n =3D n.div 10
end
sum
end
 
M

Martin DeMello

Really stumped here.

def sum_digits(n)
=A0 =A0sum =3D 0
=A0 =A0while n>0
=A0 =A0 =A0 sum +=3D n % 10
=A0 =A0 =A0 n /=3D 10
=A0 =A0 =A0 end
=A0 =A0sum
=A0end

STDOUT.sync=3Dtrue

puts sum_digits(12) #=3D> 3

require 'mathn'
puts sum_digits(12) # hangs

n /=3D 10 just keeps making n into a smaller and smaller rational. it
never reaches 0

martin
 
S

Siep Korteling

Martin said:
n /= 10 just keeps making n into a smaller and smaller rational. it
never reaches 0

martin

Yes, that's clear. Thanks for the help (real fast), Christopher and
Martin.

Siep
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,176
Messages
2,570,949
Members
47,500
Latest member
ArianneJsb

Latest Threads

Top