Skip to content

Commit

Permalink
Integer#primitive_roots: Add
Browse files Browse the repository at this point in the history
  • Loading branch information
runpaint committed Mar 14, 2010
1 parent 128fdcf commit 67f6cd1
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/numb/primitive_root.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
class Integer
def primitive_root?(g=nil)
if g
return true if g.zero? and self == 1
coprime?(g) and g.modulo_order(self) == totient
else
return true if [1, 2, 4].include?(self)
Expand Down
6 changes: 6 additions & 0 deletions lib/numb/primitive_roots.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
class Integer
def primitive_roots
return [] unless primitive_root?
(0..self).select{|n| primitive_root?(n)}
end
end
4 changes: 4 additions & 0 deletions spec/numb/primitive_root_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,8 @@
n.should be_primitive_root(7)
end
end

it "returns true when asked whether 0 is a primitive root of unity" do
1.should be_primitive_root(0)
end
end
34 changes: 34 additions & 0 deletions spec/numb/primitive_roots_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
describe Integer, "#primitive_roots" do
# A046144
@seq = [1,1,1,1,2,1,2,0,2,2,4,0,4,2,0,0,8,2,6,0,0,4,10,0,
8,4,6,0,12,0,8,0,0,8,0,0,12,6,0,0,16,0,12,0,0,10,
22,0,12,8,0,0,24,6,0,0,0,12,28,0,16,8,0,0,0,0,20,
0,0,0,24,0,24,12,0,0,0,0,24,0,18,16,40,0,0,12,0,0,
40,0,0]

@seq.to_enum.with_index(1).each do |count,n|
pr = n.primitive_roots
it "returns #{count} primitive roots for #{n}" do
pr.size.should == count
pr.uniq.size.should == pr.size
end

pr.sample(2).each do |root|
it "returns actual primitive roots, e.g. #{root} for #{n}" do
n.primitive_root?(root)
end
end
end

# A046146
@seq = [0,0,1,2,3,3,5,5,0,5,7,8,0,11,5,0,0,14,11,15,0,0,
19,21,0,23,19,23,0,27,0,24,0,0,31,0,0,35,33,0,0,
35,0,34,0,0,43,45,0,47,47,0,0,51,47,0,0,0,55,56,0,
59,55,0,0,0,0,63,0,0,0,69,0,68,69,0,0,0,0,77,0,77,
75,80,0,0].each_with_index.to_a.sample(15).each do |largest, n|
next if largest.zero?
it "returns #{largest} as the largest primitive root of #{n}" do
n.primitive_roots.max.should == largest
end
end
end

0 comments on commit 67f6cd1

Please sign in to comment.