sum_digits
This function was primarily motivated by the script. I saw an interesting mathematical fact that (17576)^(1/3) = 1+7+5+7+6 = 26 or the cube root equals the sum of the digits. So I decided to write a script that searched for numbers that satisfied this criterion for arbitrary nth roots. However, I needed an efficient method for calculating the sum of the digits and I could not find any answers that provided the necessary efficiency in MATLAB so I wrote the function. The key to its efficiency is the fact that it can handle a vector of numbers.
This allowed me to calculate the sum of the digits of 99,999,999 numbers in under a minute and was limited by the computer's memory, not computational power. The script works well for most values of n (but I am concerned with accuracy at very large values). The values for n=2,3,4 are in the screenshot.
Some other solutions:
(34012224)^(1/6) = 3+4+0+1+2+2+2+4 = 18
(248155780267521)^(1/8) = 2+4+8+1+5+5+7+8+0+2+6+7+5+2+1 = 63
(196715135728956538880)^(1/10) = 1+9+6+7+1+5+1+3+5+7+2+8+9+5+6+5+3+8+8+8+0 = 107
%----------------------------------------------
% sum_digits.m
% Computes the sum of the input vectors digits
%----------------------------------------------
% dsum = sum_digits(x)
% x : vector of values
% dsum : vector of digit sums
%----------------------------------------------
% Example
% [7 6 10] = sum_digits([43 6 235])
% 7 = 4 + 3
% 6 = 6
% 10 = 2 + 3 + 5
%----------------------------------------------
Related items:
- Submission 32047 is in script form and uses a slightly different algorithm
http://www.mathworks.com/matlabcentral/fileexchange/32047-find-sum-of-digits-in-a-number-like-4209=15
- numlib::sumOfDigits for the MuPAD Notebook Interface but not available in MATLAB
http://www.mathworks.com/help/symbolic/mupad_ref/numlib-sumofdigits.html
- Various answered questions on MATLAB Central
http://www.mathworks.com/matlabcentral/answers/5622-sum-of-digits
Zitieren als
Daniel R. Herber (2025). sum_digits (https://www.mathworks.com/matlabcentral/fileexchange/45695-sum_digits), MATLAB Central File Exchange. Abgerufen.
Kompatibilität der MATLAB-Version
Plattform-Kompatibilität
Windows macOS LinuxKategorien
Tags
Quellenangaben
Inspiriert von: Find sum of digits in a number (like 4209=15)
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!Live Editor erkunden
Erstellen Sie Skripte mit Code, Ausgabe und formatiertem Text in einem einzigen ausführbaren Dokument.
Version | Veröffentlicht | Versionshinweise | |
---|---|---|---|
1.0.0.0 |