Ryan Glass - 9 months ago 116

Ruby Question

`1.upto(sums) do |n|`

puts harmonic_sum(n)

end

is there a way to label whatever is outputed so if the user enters 6 it counts them as 1 2 3 4 5 6?

Answer Source

The harmonic series isn't implemented in Ruby standard library, but Rational is :

```
def harmonic_sum(n)
(1..n).inject(Rational(0,1)) {|r, i| r + Rational(1,i) }
end
puts harmonic_sum(5)
#=> 137/60
puts harmonic_sum(50)
#=> 13943237577224054960759/3099044504245996706400
puts harmonic_sum(10_000).to_f
#=> 9.787606036044382
```

NOTE: Your code is fine BTW. Here are some slight modifications and a few TODOS ;)

```
class Fraction
attr_reader :numerator, :denominator
def initialize(n, d)
@numerator = n
@denominator = d
end
def to_f
numerator.to_f/denominator
end
#TODO: Add *
#TODO: Define - and / with + and *
#TODO: Check that rhs is a Fraction, convert self to float otherwise.
def +(rhs)
n = @numerator*rhs.denominator + @denominator*rhs.numerator
d = @denominator*rhs.denominator
n, d = reduce(n, d)
return Fraction.new(n, d)
end
def to_s
"#{@numerator} / #{@denominator}"
end
private
def reduce(n, d)
r = gcd(n, d)
return n / r, d / r
end
def gcd(a, b)
if a % b == 0
return b
else
return gcd(b, a % b)
end
end
end
def harmonic_sum(n)
(1..n).inject(Fraction.new(0,1)) {|r, i| r + Fraction.new(1,i) }
end
puts harmonic_sum(100)
#=> 14466636279520351160221518043104131447711 / 2788815009188499086581352357412492142272
```