谐波系列

时间:2016-11-06 06:48:54

标签: ruby

1.upto(sums) do |n|

    puts harmonic_sum(n)

end

有没有办法标记输出的内容,如果用户输入6,则将它们计为1 2 3 4 5 6?

1 个答案:

答案 0 :(得分:2)

谐波系列没有在Ruby标准库中实现,但Rational是:

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

注意:您的代码很好BTW。这里有一些细微的修改和一些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