Владимир обнови решението на 15.10.2013 02:03 (преди около 11 години)
+class Integer
+ def prime?
+ 2.upto(pred).all? { |n| remainder(n).nonzero? }
+ end
+
+ def fermat_factorization
+ a = Math.sqrt(self).ceil
+ b = a*a - self
+ until Math.sqrt(b) % 1 == 0
+ puts Math.sqrt(b)
+ b = b + 2*a + 1
+ end
+ return [(a - Math.sqrt(b)).to_i, (a + Math.sqrt(b)).to_i] - [1]
+ end
+
+ def prime_factors
+ factors = []
+ self.abs.fermat_factorization.each do |n|
+ if n.prime?
+ factors << n
+ else
+ factors = factors + n.prime_factors
+ end
+ end
+ return factors.sort
+ end
+
+ def harmonic
+ return nil if self <= 0
+ harmonic_number = Rational(1)
+ 2.upto(self) do |n|
+ harmonic_number += (Rational(1) / n)
+ end
+ return harmonic_number
+ end
+
+ def digits
+ self.abs.to_s.scan(/./).map { |n| n.to_i }
+ end
+end
+
+class Array
+ def frequencies
+ frequency = {}
+ self.each do |n|
+ frequency[n] = 1 + frequency.fetch(n, 0)
+ end
+ return frequency
+ end
+
+ def average
+ return nil if self.size.zero?
+ asd = self.inject { |sum, i| sum + i }.to_f / size
+ end
+
+ def drop_every n
+ puts n
+ filtered = []
+ self.each_with_index { |e,i| filtered << e unless (i+1).remainder(n).zero? }
+ return filtered
+ end
+
+ def combine_with other
+ combined = []
+ 0.upto([self.size, other.size].max) do |i|
+ combined << self[i] if self[i]
+ combined << other[i] if other[i]
+ end
+ return combined
+ end
+end