Skip to content

Commit

Permalink
- Added the Number digital_root(n,b=10) method.
Browse files Browse the repository at this point in the history
Returns the digital root of `n`, with respect to base `b`.

    say 30.of { .digital_root }               #=> OEIS: A010888
    say 30.of { .digital_root(.isqrt+1) }     #=> OEIS: A122197

Also known as "repeated digital sum".

Both `n` and `b` can be arbitrary large, as long as b > 1.
  • Loading branch information
trizen committed May 5, 2022
1 parent 389d2c1 commit ce91e59
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
30 changes: 30 additions & 0 deletions lib/Sidef/Types/Number/Number.pm
Original file line number Diff line number Diff line change
Expand Up @@ -6716,6 +6716,36 @@ package Sidef::Types::Number::Number {
Sidef::Types::Array::Array->new([map { $_ ? ONE : ZERO } split(//, $bin)]);
}

sub digital_root {
my ($n, $base) = @_;

# Formula:
# digital_root(n,b) = n - (b-1)*floor((n-1)/(b-1))

$n = _any2mpz($$n) // goto &nan;

if (defined($base)) {
_valid(\$base);
$base = _any2mpz($$base) // goto &nan;
Math::GMPz::Rmpz_cmp_ui($base, 1) > 0 or goto &nan;
}
else {
$base = $TEN;
}

Math::GMPz::Rmpz_sgn($n) || return ZERO;

my $r = Math::GMPz::Rmpz_init();
my $t = Math::GMPz::Rmpz_init();

Math::GMPz::Rmpz_sub_ui($r, $n, 1);
Math::GMPz::Rmpz_sub_ui($t, $base, 1);
Math::GMPz::Rmpz_mod($r, $r, $t);
Math::GMPz::Rmpz_add_ui($r, $r, 1);

bless \$r;
}

sub expnorm {
my ($n, $base) = @_;

Expand Down
15 changes: 15 additions & 0 deletions lib/Sidef/Types/Number/Number.pod
Original file line number Diff line number Diff line change
Expand Up @@ -1851,6 +1851,21 @@ It also supports negative indices:

=cut

=head2 digital_root

digital_root(n, b=10)

Returns the digital root of C<n>, with respect to base C<b>.

say 30.of { .digital_root } #=> OEIS: A010888
say 30.of { .digital_root(.isqrt+1) } #=> OEIS: A122197

Also known as "repeated digital sum".

Both C<n> and C<b> can be arbitrary large, as long as b > 1.

=cut

=head2 digits

n.digits(b=10)
Expand Down

0 comments on commit ce91e59

Please sign in to comment.