Skip to content

Commit bc2fbef

Browse files
authored
Add specialized +, -, rem and mod for Rational and Integer (JuliaLang#35444)
1 parent b773beb commit bc2fbef

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

base/rational.jl

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,14 @@ for (op,chop) in ((:+,:checked_add), (:-,:checked_sub),
263263
xd, yd = divgcd(x.den, y.den)
264264
Rational(($chop)(checked_mul(x.num,yd), checked_mul(y.num,xd)), checked_mul(x.den,yd))
265265
end
266+
267+
function ($op)(x::Rational, y::Integer)
268+
Rational(($chop)(x.num, checked_mul(x.den, y)), x.den)
269+
end
270+
271+
function ($op)(y::Integer, x::Rational)
272+
Rational(($chop)(checked_mul(x.den, y), x.num), x.den)
273+
end
266274
end
267275
end
268276

@@ -479,4 +487,3 @@ function gcdx(x::Rational, y::Rational)
479487
end
480488
c, a, b
481489
end
482-

test/rational.jl

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -405,3 +405,22 @@ end
405405
@test gcd([5, 2, 1//2]) == 1//2
406406
end
407407

408+
@testset "Binary operations with Integer" begin
409+
@test 1//2 - 1 == -1//2
410+
@test -1//2 + 1 == 1//2
411+
@test 1 - 1//2 == 1//2
412+
@test 1 + 1//2 == 3//2
413+
for q in (19//3, -4//5), i in (6, -7)
414+
@test rem(q, i) == q - i*div(q, i)
415+
@test mod(q, i) == q - i*fld(q, i)
416+
end
417+
418+
@test_throws OverflowError UInt(1)//2 - 1
419+
@test_throws OverflowError 1 - UInt(5)//2
420+
@test_throws OverflowError 1//typemax(Int64) + 1
421+
@test_throws OverflowError Int8(1) + Int8(5)//(Int8(127)-Int8(1))
422+
423+
@test Int8(1) + Int8(4)//(Int8(127)-Int8(1)) == Int8(65) // Int8(63)
424+
@test -Int32(1) // typemax(Int32) - Int32(1) == typemin(Int32) // typemax(Int32)
425+
@test 1 // (typemax(Int128) + BigInt(1)) - 2 == (1 + BigInt(2)*typemin(Int128)) // (BigInt(1) + typemax(Int128))
426+
end

0 commit comments

Comments
 (0)