sum_digits

版本 1.0.0.0 (1.5 KB) 作者: Daniel R. Herber
Find the sum of digits of a vector and an interesting script that uses it
343.0 次下载
更新时间 2014/2/26

查看许可证

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

引用格式

Daniel R. Herber (2024). sum_digits (https://www.mathworks.com/matlabcentral/fileexchange/45695-sum_digits), MATLAB Central File Exchange. 检索来源 .

MATLAB 版本兼容性
创建方式 R2013b
兼容任何版本
平台兼容性
Windows macOS Linux
类别
Help CenterMATLAB Answers 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!
版本 已发布 发行说明
1.0.0.0