Skip to content
This repository has been archived by the owner on Sep 12, 2018. It is now read-only.

Commit

Permalink
Browse files Browse the repository at this point in the history
Fixed the RSA::Math.phi method to use arbitrary-precision decimal cal…
…culations.

Floating-point inaccuracies were previously coming into play at around n = 10^24. With the new implementation, no incidental limits are placed on the size of n.
  • Loading branch information
artob committed Sep 9, 2010
1 parent 92d48f9 commit 5aa2784
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
4 changes: 3 additions & 1 deletion lib/rsa/math.rb
Expand Up @@ -165,6 +165,8 @@ def self.modpow(base, exponent, modulus)
result
end

ONE = BigDecimal('1')

##
# Returns the Euler totient for the positive integer `n`.
#
Expand All @@ -181,7 +183,7 @@ def self.phi(n)
when n < 0 then raise ArgumentError, "expected a positive integer, but got #{n}"
when n < 2 then 1 # by convention
when prime?(n) then n - 1
else factorize(n).inject(n) { |product, (p, e)| product * (1 - (1 / p.to_f)) }.to_i # FIXME: use BigDecimal
else factorize(n).inject(n) { |product, (p, e)| product * (ONE - (ONE / BigDecimal(p.to_s))) }.round.to_i
end
end

Expand Down
15 changes: 11 additions & 4 deletions spec/math_spec.rb
Expand Up @@ -200,12 +200,20 @@
context "RSA::Math.phi(n) for n > 2" do
it "returns an even integer" do
# @see http://en.wikipedia.org/wiki/Euler's_totient_function#Properties
3.upto(10_000).each do |n|
3.upto(10_000) do |n|
RSA::Math.phi(n).should be_even
end
end
end

context "RSA::Math.phi(n) when n is prime" do
it "returns n - 1" do
2.upto(10_000) do |n|
RSA::Math.phi(n).should == n - 1 if RSA::Math.prime?(n)
end
end
end

context "RSA::Math.phi(n) for n = 1..69" do
it "returns \u03D5(n)" do
# @see http://oeis.org/classic/A000010
Expand All @@ -216,10 +224,9 @@
end
end

context "RSA::Math.phi(10^e) for e = 1..23" do
context "RSA::Math.phi(10^e) for e = 1..1000" do
it "returns \u03D5(n)" do
# Floating-point inaccuracies come into play at around n = 10^24.
(1..23).each do |e|
1.upto(1_000) do |e|
RSA::Math.phi(n = 10**e).should == ('4' + '0' * (e - 1)).to_i # RSA::Math.phi(n) == 0.4 * n
end
end
Expand Down

0 comments on commit 5aa2784

Please sign in to comment.