Skip to content

Commit

Permalink
A more thorough handling of is-prime
Browse files Browse the repository at this point in the history
- sub is-prime now just passes on to method handling
- Cool.is-prime now just numerifies
- added optimised Num and Rational candidates
  • Loading branch information
lizmat committed Dec 25, 2017
1 parent f01c50f commit 2370196
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 13 deletions.
3 changes: 1 addition & 2 deletions src/core/Cool.pm
Expand Up @@ -34,8 +34,7 @@ my class Cool { # declared in BOOTSTRAP
method cotanh() { self.Numeric.cotanh }
method acotanh() { self.Numeric.acotanh }
method cis() { self.Numeric.cis }

method is-prime(--> Bool:D) { self.Int.is-prime }
method is-prime(--> Bool:D) { self.Numeric.is-prime }

proto method log(|) {*}
multi method log(Cool:D: ) { self.Numeric.log }
Expand Down
13 changes: 2 additions & 11 deletions src/core/Int.pm
Expand Up @@ -137,9 +137,7 @@ my class Int does Real { # declared in BOOTSTRAP
method expmod(Int:D: Int:D \base, Int:D \mod) {
nqp::expmod_I(self, nqp::decont(base), nqp::decont(mod), Int);
}
method is-prime(Int:D: --> Bool:D) {
nqp::p6bool(nqp::isprime_I(self, nqp::unbox_i(100)));
}
method is-prime(--> Bool:D) { nqp::p6bool(nqp::isprime_I(self,100)) }

method floor(Int:D:) { self }
method ceiling(Int:D:) { self }
Expand Down Expand Up @@ -446,14 +444,7 @@ multi sub chr(int $x --> str) {
nqp::chr($x);
}

proto sub is-prime($) is pure {*}
multi sub is-prime(Int:D \i) {
nqp::p6bool(nqp::isprime_I(nqp::decont(i), nqp::unbox_i(100)));
}
multi sub is-prime(\i) {
i == i.floor
&& nqp::p6bool(nqp::isprime_I(nqp::decont(i.Int), nqp::unbox_i(100)));
}
sub is-prime(\x) is pure { x.is-prime }

proto sub expmod($, $, $) is pure {*}
multi sub expmod(Int:D \base, Int:D \exp, Int:D \mod) {
Expand Down
12 changes: 12 additions & 0 deletions src/core/Num.pm
Expand Up @@ -242,6 +242,18 @@ my class Num does Real { # declared in BOOTSTRAP
multi method acotanh(Num:D: ) {
(1e0 / self).atanh;
}
method is-prime(--> Bool:D) {
nqp::p6bool(
nqp::if(
nqp::isnanorinf(self),
False,
nqp::if(
nqp::iseq_n(self,nqp::floor_n(self)),
nqp::fromnum_I(self,Int).is-prime
)
)
)
}

method narrow(Num:D:) {
my $i := self.Int;
Expand Down
4 changes: 4 additions & 0 deletions src/core/Rational.pm
Expand Up @@ -81,6 +81,10 @@ my role Rational[::NuT = Int, ::DeT = ::("NuT")] does Real {
)
}

method is-prime(--> Bool:D) {
nqp::if($!denominator == 1,$!numerator.is-prime)
}

multi method Str(::?CLASS:D:) {
if nqp::istype($!numerator,Int) {
my $whole = self.abs.floor;
Expand Down

0 comments on commit 2370196

Please sign in to comment.