[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Why does mathn kill this method?

Siep Korteling

3/31/2009 10:46:00 PM

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?
--
Posted via http://www.ruby-....

3 Answers

Christopher Dicely

3/31/2009 11:05:00 PM

0

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

Martin DeMello

3/31/2009 11:06:00 PM

0

On Wed, Apr 1, 2009 at 4:16 AM, Siep Korteling <s.korteling@gmail.com> wrot=
e:
> 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

Siep Korteling

3/31/2009 11:16:00 PM

0

Martin DeMello wrote:
> On Wed, Apr 1, 2009 at 4:16 AM, Siep Korteling <s.korteling@gmail.com>
> wrote:
>>
>> STDOUT.sync=true
>>
>> puts sum_digits(12) #=> 3
>>
>> require 'mathn'
>> puts sum_digits(12) # hangs
>
> 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
--
Posted via http://www.ruby-....