Skip to content

Commit

Permalink
Merge pull request #2252 from natalie-lang/rb/integer-ceildiv
Browse files Browse the repository at this point in the history
Implement Integer#ceildiv
  • Loading branch information
seven1m authored Oct 7, 2024
2 parents bea0b50 + d1eee6d commit fc5709c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
22 changes: 22 additions & 0 deletions spec/core/integer/ceildiv_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
require_relative '../../spec_helper'

describe "Integer#ceildiv" do
ruby_version_is '3.2' do
it "returns a quotient of division which is rounded up to the nearest integer" do
0.ceildiv(3).should eql(0)
1.ceildiv(3).should eql(1)
3.ceildiv(3).should eql(1)
4.ceildiv(3).should eql(2)

4.ceildiv(-3).should eql(-1)
-4.ceildiv(3).should eql(-1)
-4.ceildiv(-3).should eql(2)

3.ceildiv(1.2).should eql(3)
3.ceildiv(6/5r).should eql(3)

(10**100-11).ceildiv(10**99-1).should eql(10)
(10**100-9).ceildiv(10**99-1).should eql(11)
end
end
end
8 changes: 5 additions & 3 deletions src/integer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ def try_convert(n)
raise TypeError, "can't convert #{n.class} to Integer (#{n.class}#to_int gives #{result.class})"
end
end
else
nil
end
end
end
Expand All @@ -31,7 +29,7 @@ def digits(radix = 10)
if radix < 0
raise ArgumentError, 'negative radix'
elsif radix < 2
raise ArgumentError, "invalid radix 0"
raise ArgumentError, 'invalid radix 0'
end

quotient = self
Expand Down Expand Up @@ -76,6 +74,10 @@ def fdiv(n)
end
end

def ceildiv(n)
-div(-n)
end

def gcdlcm(n)
[gcd(n), lcm(n)]
end
Expand Down

0 comments on commit fc5709c

Please sign in to comment.