| 1 | package Crypt::Perl::Math; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use Crypt::Perl::BigInt (); | ||
| 7 | use Crypt::Perl::RNG (); | ||
| 8 | |||
| 9 | sub ceil { | ||
| 10 | return int($_[0]) if $_[0] <= 0; | ||
| 11 | |||
| 12 | return int($_[0]) + int( !!($_[0] - int $_[0]) ); | ||
| 13 | } | ||
| 14 | |||
| 15 | #limit is inclusive | ||
| 16 | #cf. Python’s random.randint() | ||
| 17 | sub randint { | ||
| 18 | my ($limit) = @_; | ||
| 19 | |||
| 20 | my $limit_bit_count; | ||
| 21 | if (ref($limit) && (ref $limit)->isa('Math::BigInt')) { | ||
| 22 | $limit_bit_count = length($limit->as_bin()) - 2; | ||
| 23 | } | ||
| 24 | |||
| 25 | #Is this ever needed?? | ||
| 26 | else { | ||
| 27 | $limit_bit_count = length sprintf '%b', $limit; | ||
| 28 | } | ||
| 29 | |||
| 30 | my $rand; | ||
| 31 | do { | ||
| 32 | $rand = Crypt::Perl::BigInt->from_bin( Crypt::Perl::RNG::bit_string($limit_bit_count) ); | ||
| 33 | } while $rand > $limit; | ||
| 34 | |||
| 35 | return $rand; | ||
| 36 | } | ||
| 37 | |||
| 38 | 1; |