Skip to content

Commit

Permalink
- Added the Number is_almost_prime(n,k).
Browse files Browse the repository at this point in the history
Return true if `n` is a k-almost prime (i.e.: true iff `n` is the product of `k` not necessarily distinct primes)

Example:

	say 20.by { .is_almost_prime(1) }	# primes
	say 20.by { .is_almost_prime(2) }	# semiprimes
	say 20.by { .is_almost_prime(3) }	# 3-almost primes
  • Loading branch information
trizen committed May 23, 2020
1 parent c46ec44 commit cbaaf31
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
61 changes: 61 additions & 0 deletions lib/Sidef/Types/Number/Number.pm
Original file line number Diff line number Diff line change
Expand Up @@ -10160,6 +10160,67 @@ package Sidef::Types::Number::Number {
: Sidef::Types::Bool::Bool::FALSE;
}

sub is_almost_prime {
my ($n, $k) = @_;

if (defined($k)) {
_valid(\$k);
$k = _any2ui($$k) // return Sidef::Types::Bool::Bool::FALSE;
}
else {
$k = 1;
}

if ($k == 0) {
return $n->is_one;
}
elsif ($k == 1) {
return $n->is_prime;
}
elsif ($k == 2) {
return $n->is_semiprime;
}

$n = $$n;

if (ref($n) ne 'Math::GMPz') {
__is_int__($n) || return Sidef::Types::Bool::Bool::FALSE;
$n = _any2mpz($n) // return Sidef::Types::Bool::Bool::FALSE;
}

my $omega = 0;
my $remainder = $n;
my $size = Math::GMPz::Rmpz_sizeinbase($n, 10);

if ($size > 30) {

my $trial_limit = 1e3;

#<<<
if ($size > 60) { $trial_limit = 1e6 }
elsif ($size > 50) { $trial_limit = 1e5 }
elsif ($size > 40) { $trial_limit = 1e4 }
#>>>

my ($r, @factors) = _native_trial_factor($n, $trial_limit);

$omega += scalar(@factors);
$remainder = $r;
}

if ($omega > $k) {
return Sidef::Types::Bool::Bool::FALSE;
}

my @factors = Math::Prime::Util::GMP::factor($remainder);

$omega += scalar(@factors);

($omega == $k)
? Sidef::Types::Bool::Bool::TRUE
: Sidef::Types::Bool::Bool::FALSE;
}

sub is_prob_prime {
my ($n) = @_;
_primality_pretest($$n)
Expand Down
8 changes: 8 additions & 0 deletions lib/Sidef/Types/Number/Number.pod
Original file line number Diff line number Diff line change
Expand Up @@ -2050,6 +2050,14 @@ Return the

=cut

=head2 is_almost_prime

Number.is_almost_prime() -> I<Obj>

Return the

=cut

=head2 is_between

Number.is_between() -> I<Obj>
Expand Down

0 comments on commit cbaaf31

Please sign in to comment.