Permalink
Browse files

Integer#reciprocal: Add; use in other methods

  • Loading branch information...
1 parent 073cac5 commit 456006cd0049dd65f870e75a4e2f839623744041 @runpaint committed Mar 27, 2010
View
@@ -240,7 +240,7 @@ def infinitary_divisors
def ore?
div = divisors
- Rational(div.size, div.map{|d| Rational(1, d)}.reduce(:+)).denominator == 1
+ Rational(div.size, div.map{|d| d.reciprocal}.reduce(:+)).denominator == 1
end
alias :harmonic_divisor? :ore?
@@ -55,4 +55,3 @@ def superabundant?
end
memoize :superabundant?
end
-
View
@@ -90,7 +90,7 @@ def octagonal?
def pyramidal(r)
n = self
- (Rational(1, 6) * n * n.succ * (((r - 2) * n) + (5 - r))).to_i
+ (6.reciprocal * n * n.succ * (((r - 2) * n) + (5 - r))).to_i
end
def octahedral
View
@@ -8,6 +8,10 @@ def cubic_residue?(p)
coprime?(p) and residue? p, 3
end
+ def reciprocal
+ self ** -1
+ end
+
private
def residue?(p, e=1)
(1...p).any?{|x| (x**e).modulo(p) == self}
View
@@ -3,7 +3,7 @@ class Integer
def φ
return 1 if self == 1
return self - 1 if prime?
- (prime_factors.uniq.map{|f| 1 - Rational(1, f)}.reduce(:*) * self).to_i
+ (prime_factors.uniq.map{|f| 1 - f.reciprocal}.reduce(:*) * self).to_i
end
alias :totient
@@ -14,7 +14,7 @@
@seq = @numerators.zip(@denominators).map{|n,d| Rational(n,d)}
@seq = ([0.to_r] * @numerators.size).zip(@seq).flatten
@seq.shift
- @seq[1] = -Rational(1, 2)
+ @seq[1] = -2.reciprocal
@seq.each_with_index do |r, n|
it "returns #{r} for #{n}" do
n.bernoulli.should == r
@@ -0,0 +1,16 @@
+# coding: utf-8
+describe Integer, "#reciprocal" do
+
+ 100.times do
+ n = rand(10**10)
+ redo if n.zero?
+ r = Rational(1, n)
+ it "returns #{r} as the reciprocal of #{n}" do
+ n.reciprocal.should == r
+ end
+ end
+
+ it "raises a ZeroDivisionError for the reciprocal of zero" do
+ ->{ 0.reciprocal }.should raise_error(ZeroDivisionError)
+ end
+end

0 comments on commit 456006c

Please sign in to comment.