Sum the digits of a number?

112 views (last 30 days)
tzenh karetzh
tzenh karetzh on 17 Jan 2014
Moved: Dyuman Joshi on 18 Sep 2023
Hi, I'd like to know how can someone add the digits of a number to the final point in matlab.
For example 525 --> 5 + 2 + 5 = 12 --> 1 + 2 = 3
I'm thinking about dividing by ten and adding the digits after the decimal point while at the same time round the number.
Any ideas on how to add the digits would be really helpfull.
Also how to identify a digit by knowing its position in a number
i.e. the 5th digit of 9483672 is 6. Thanks in advance
  2 Comments
José-Luis
José-Luis on 17 Jan 2014
Is this homework?
tzenh karetzh
tzenh karetzh on 17 Jan 2014
Not exactly.My homework is to find the prime numbers in a certain space. This is just a question that came to me because we know that numbers like 711 that their digits add up to 3,6 or 9 can be divided by 3.For the prime numbers it's much easier to go for mod(number,3). And maybe it can be useful to someone else for other use

Sign in to comment.

Answers (7)

Les Beckham
Les Beckham on 2 May 2020
Edited: Les Beckham on 2 May 2020
I know it sounds too easy to be true but this manipulation is actually the same as modulo 9. No loops or string conversions needed.
>> mod(525,9)
ans =
3
>> mod(9483672,9)
ans =
3
For the second part of your question, try this:
function [out] = extract_digit(num,digit)
%EXTRACT_DIGIT Return the specified digit from a number
out = num2str(num);
out = out(digit);
end
  4 Comments
Dimitri
Dimitri on 6 Apr 2021
This won't work...mod(45,9) give zero..but what he wants is 9.
John D'Errico
John D'Errico on 6 Apr 2021
@Dimitri Assuming you want to keep on re-summing the digits until the sum is a single digit number... then special case handling still will work. You just need to think about what happens.
The ONLY case where that digit sum is zero is when the number is itself zero. Therefore, if the number is NOT zero, but the modulus was zero, then the digit sum would have been 9.
As such we can see a simple solution:
N = 12345678;
if N == 0
digsum = 0;
else
digsum = mod(N,9);
if digsum == 0
digsum = 9;
end
end
digsum
digsum = 9
Is that algorithm correct for N larger than 0? Clearly it works when N == 9. We can write a really simple code to compute the sum of the digits directly, for just one iteration, and then just iterate until it is done.
dsum = @(n) sum(dec2base(n,10) - '0');
digsum = N;
while digsum > 9
digsum = dsum(digsum);
end
digsum
digsum = 9

Sign in to comment.


Azzi Abdelmalek
Azzi Abdelmalek on 17 Jan 2014
a=525;
b=num2str(a);
while numel(b)>1
a=sum(str2double(regexp(b,'\d','match')));
b=num2str(a);
end
out=str2num(b)
% -------------------------------
a=9483672;
b=num2str(a);
b(5)
  2 Comments
rohan dhane
rohan dhane on 15 Nov 2019
you are fanta.......
Stephen23
Stephen23 on 15 Nov 2019
Edited: Stephen23 on 15 Nov 2019
Simpler without regexp and str2double:
a = 525;
b = num2str(a);
while numel(b)>1
a = sum(b-'0');
b = num2str(a);
end
out = a;

Sign in to comment.


Sean de Wolski
Sean de Wolski on 17 Jan 2014

Ans sadiq
Ans sadiq on 19 Aug 2021
function out=digit_sum(in)
q=in;
a=q/10;
b=floor(a);
c=q-b*10;
w=c;
if q>0
w=w+digit_sum(b);
end
out=w;
end

Pablo López
Pablo López on 5 Feb 2019
You can try this:
n = 525;
sum(str2num(num2str(sum(str2num(num2str(n)')))'))
  4 Comments
Stephen23
Stephen23 on 6 Feb 2019
Edited: Stephen23 on 6 Feb 2019
The question gave this example:
"For example 525 --> 5 + 2 + 5 = 12 --> 1 + 2 = 3"
which indicates that the 12 digits should also be summed to 3. Usually when this task is given, it is required to continue summing until only one digit is reached (and this is what the other answers do). In contrast, your code sums twice only, regardless of how many digits remain. This may or may not be the intended behavior, it depends entirely on the specifications requested by the assignment. I just wanted to note the distinction.
Pablo López
Pablo López on 6 Feb 2019
Well seen! Thank you for your observation.

Sign in to comment.


Image Analyst
Image Analyst on 7 Apr 2021
Here is how I did it:
fprintf('Beginning to run %s.m ...\n', mfilename);
% Get a random integer.
originalNumber = int64(randi(2^53-1, 1, 1))
% Do the first iteration.
strNumbers = num2str(originalNumber);
intNumbers = strNumbers - '0'
loopCounter = 1;
maxIterations = 100; % The Failsafe (so we never get an infinite loop due to a logic error). Every while loop should always have a failsafe.
while length(intNumbers) >= 2 && loopCounter < maxIterations
theSum = sum(intNumbers);
fprintf('After %d iterations, the number is %s and the sum of its digits is %d\n',...
loopCounter, strNumbers, theSum);
% Prepare the next iteration:
strNumbers = num2str(theSum);
intNumbers = num2str(theSum) - '0';
loopCounter = loopCounter + 1;
end
fprintf('Done running %s.m ...\n', mfilename);
I get:
int64
7208285642958972
intNumbers =
7 2 0 8 2 8 5 6 4 2 9 5 8 9 7 2
After 1 iterations, the number is 7208285642958972 and the sum of its digits is 84
After 2 iterations, the number is 84 and the sum of its digits is 12
After 3 iterations, the number is 12 and the sum of its digits is 3

Javier Echanobe
Javier Echanobe on 15 Sep 2023
Edited: Javier Echanobe on 15 Sep 2023
n=round(1000*rand(1))
SUM=sum(num2str(n))-48*length(num2str(n)) % 48 is the ASCII code for 0
________________
When I execute this code I obtain:
n =
633
SUM =
12
  4 Comments
Dyuman Joshi
Dyuman Joshi on 15 Sep 2023
@Stephen23, I also figured that it does something different.
But from @Javier Echanobe's line "When I execute this code I obtain", I assumed that they were trying to do the same as the original question, but could not achieve it.
Hence my comment.
Javier Echanobe
Javier Echanobe on 18 Sep 2023
Moved: Dyuman Joshi on 18 Sep 2023
n=round(1000*rand(1))
n = 985
SUM=sum(num2str(n))-48*length(num2str(n)); % 48 is the ASCII code for 0
while SUM>9
SUM=sum(num2str(SUM))-48*length(num2str(SUM));
end
SUM
SUM = 4
You are right.
This code does make it.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!