Sum of digits of an integer
MuPAD® notebooks are not recommended. Use MATLAB® live scripts instead.
MATLAB live scripts support most MuPAD functionality, though there are some differences. For more information, see Convert MuPAD Notebooks to MATLAB Live Scripts.
numlib::sumOfDigits(n, base) computes the
sum of digits of
n in the given base
if the base is not given, it defaults to 10.
The sum of digits may be larger than the base. For certain purposes
(testing divisibility by b -
1, where b is
the base), it may be useful to apply
and over to the result. This is not done automatically. See Example 2.
We compute the decimal and the binary sum of digits of 11:
numlib::sumOfDigits(11), numlib::sumOfDigits(11, 2)
We want to test whether 9 divides a given number, using the school method:
n:= 24373463462374324: repeat n:= numlib::sumOfDigits(n); print(n) until n < 10 end: delete n:
This only makes sense for demonstration purposes, as the following command achieves the same but much faster:
24373463462374324 mod 9
Integer greater than one