Skip to content

Commit

Permalink
- Added Number is_palindrome(n, b=10) method.
Browse files Browse the repository at this point in the history
Returns true if the given number `n` is palindromic in the given base `b`. When no base is given, it defaults to 10.

Example:

	# Numbers that are palindromic in bases 2 and 10 (OEIS: A007632)
	say 1e6.range.grep{ .is_palindrome(2) && .is_palindrome(10) }
  • Loading branch information
trizen committed Oct 27, 2019
1 parent ce55a1a commit 5219b68
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 2 deletions.
46 changes: 44 additions & 2 deletions lib/Sidef/Types/Number/Number.pm
Original file line number Diff line number Diff line change
Expand Up @@ -9314,13 +9314,16 @@ package Sidef::Types::Number::Number {

# Using Thomas Ordowski's criterion from A050217.
my @factors =
map { ($_ < ULONG_MAX) ? ($_ - 1) : Math::GMPz::Rmpz_init_set_str("$_", 10) - 1 } Math::Prime::Util::GMP::factor($n);
map { ($_ < ULONG_MAX) ? ($_ - 1) : (Math::GMPz::Rmpz_init_set_str("$_", 10) - 1) }
Math::Prime::Util::GMP::factor($n);

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

@bases = (2) if !@bases;

foreach my $base (@bases) {
Math::Prime::Util::GMP::powmod($base, $gcd, $n) eq '1' or return Sidef::Types::Bool::Bool::FALSE;
Math::Prime::Util::GMP::powmod($base, $gcd, $n) eq '1'
or return Sidef::Types::Bool::Bool::FALSE;
}

return Sidef::Types::Bool::Bool::TRUE;
Expand Down Expand Up @@ -12262,6 +12265,45 @@ package Sidef::Types::Number::Number {
bless \__polygonal_root__(_any2mpfr_mpc($$x), _any2mpfr_mpc($$y), 1);
}

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

__is_int__($$n) || return Sidef::Types::Bool::Bool::FALSE;
$n = _any2mpz($$n) // return Sidef::Types::Bool::Bool::FALSE;

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

# Optimization for bases <= 62
if (!defined($k) or Math::GMPz::Rmpz_cmp_ui($k, 62) <= 0) {

$k = defined($k) ? Math::GMPz::Rmpz_get_ui($k) : 10;

# Return False if base is <= 1
$k <= 1 and return Sidef::Types::Bool::Bool::FALSE;

my $str = Math::GMPz::Rmpz_get_str($n, $k);

return (
($str eq reverse($str))
? Sidef::Types::Bool::Bool::TRUE
: Sidef::Types::Bool::Bool::FALSE
);
}

my @digits = @{$_[0]->digits($_[1])};
my $len = scalar(@digits) - 1;

foreach my $i (0 .. ($len >> 1)) {
Math::GMPz::Rmpz_cmp(${$digits[$i]}, ${$digits[$len - $i]})
&& return Sidef::Types::Bool::Bool::FALSE;
}

return Sidef::Types::Bool::Bool::TRUE;
}

sub shift_left {
my ($x, $y) = @_;

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 @@ -2196,6 +2196,14 @@ Return the

=cut

=head2 is_palindrome

Number.is_palindrome() -> I<Obj>

Return the

=cut

=head2 is_perrin_pseudoprime

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

0 comments on commit 5219b68

Please sign in to comment.