Christopher Dicely
3/31/2009 11:05:00 PM
On Tue, Mar 31, 2009 at 3:46 PM, Siep Korteling <s.korteling@gmail.com> wro=
te:
> 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