Skip to content

Commit

Permalink
- Performance improvement in Number squarefree_count(n) for n > 2^40.
Browse files Browse the repository at this point in the history
If Math::Prime::Util is installed, we now use it to iterate over the factored squarefree numbers <= sqrt(n).
  • Loading branch information
trizen committed Jan 31, 2021
1 parent a13c77e commit 197215d
Showing 1 changed file with 19 additions and 7 deletions.
26 changes: 19 additions & 7 deletions lib/Sidef/Types/Number/Number.pm
Original file line number Diff line number Diff line change
Expand Up @@ -9629,9 +9629,7 @@ package Sidef::Types::Number::Number {
: Math::Prime::Util::GMP::moebius(1, $s)
) {
++$k;
if ($m) {
$count += $m * CORE::int($n / ($k * $k));
}
$count += $m * CORE::int($n / ($k * $k)) if $m;
}

return (
Expand All @@ -9642,12 +9640,26 @@ package Sidef::Types::Number::Number {
}

# Linear counting up to sqrt(n)
my ($count, $m) = 0;
foreach my $k (1 .. $s) {
if ($m = Math::Prime::Util::GMP::moebius($k)) {
$count += $m * CORE::int($n / ($k * $k));

my $count = 0;

if (HAS_PRIME_UTIL) {
Math::Prime::Util::forsquarefree(
sub {
$count += ((scalar(@_) & 1) ? -1 : 1) * CORE::int($n / ($_ * $_));
},
$s
);
}
else {
my $m;
foreach my $k (1 .. $s) {
if ($m = Math::Prime::Util::GMP::moebius($k)) {
$count += $m * CORE::int($n / ($k * $k));
}
}
}

return (
($count < ULONG_MAX)
? __PACKAGE__->_set_uint($count)
Expand Down

0 comments on commit 197215d

Please sign in to comment.