Skip to content

Truncated quotient and remainder #14948

@HertzDevil

Description

@HertzDevil

Number has a #divmod method, which returns the floored quotient (#//) and the modulus (#%) as a 2-tuple:

crystal/src/number.cr

Lines 217 to 219 in 791b0e4

def divmod(number)
{(self // number).floor, self % number}
end

There is no counterpart for the truncated quotient (#tdiv) and remainder (#remainder). Two examples in the standard library are:

crystal/src/int.cr

Lines 667 to 668 in 791b0e4

ary << num.remainder(base).to_i
num = num.tdiv(base)

crystal/src/time/span.cr

Lines 68 to 69 in 791b0e4

@seconds = seconds.to_i64 + nanoseconds.tdiv(NANOSECONDS_PER_SECOND).to_i64
@nanoseconds = nanoseconds.remainder(NANOSECONDS_PER_SECOND).to_i32

BigInt also has a specialized function for computing both results together, similar to its current #divmod override. I think we should add such a method for completeness. In other languages:

If we want to emphasize the similarity with the floored version, #tdivmod is also a possible candidate.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions