Sum the digits of a number?

115 visualizaciones (últimos 30 días)
tzenh karetzh
tzenh karetzh el 17 de En. de 2014
Movida: Dyuman Joshi el 18 de Sept. de 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 comentarios
José-Luis
José-Luis el 17 de En. de 2014
Is this homework?
tzenh karetzh
tzenh karetzh el 17 de En. de 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

Iniciar sesión para comentar.

Respuestas (7)

Les Beckham
Les Beckham el 2 de Mayo de 2020
Editada: Les Beckham el 2 de Mayo de 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 comentarios
Dimitri
Dimitri el 6 de Abr. de 2021
This won't work...mod(45,9) give zero..but what he wants is 9.
John D'Errico
John D'Errico el 6 de Abr. de 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

Iniciar sesión para comentar.


Azzi Abdelmalek
Azzi Abdelmalek el 17 de En. de 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 comentarios
rohan dhane
rohan dhane el 15 de Nov. de 2019
you are fanta.......
Stephen23
Stephen23 el 15 de Nov. de 2019
Editada: Stephen23 el 15 de Nov. de 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;

Iniciar sesión para comentar.


Sean de Wolski
Sean de Wolski el 17 de En. de 2014

Ans sadiq
Ans sadiq el 19 de Ag. de 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 el 5 de Feb. de 2019
You can try this:
n = 525;
sum(str2num(num2str(sum(str2num(num2str(n)')))'))
  4 comentarios
Stephen23
Stephen23 el 6 de Feb. de 2019
Editada: Stephen23 el 6 de Feb. de 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 el 6 de Feb. de 2019
Well seen! Thank you for your observation.

Iniciar sesión para comentar.


Image Analyst
Image Analyst el 7 de Abr. de 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 el 15 de Sept. de 2023
Editada: Javier Echanobe el 15 de Sept. de 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 comentarios
Dyuman Joshi
Dyuman Joshi el 15 de Sept. de 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 el 18 de Sept. de 2023
Movida: Dyuman Joshi el 18 de Sept. de 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.

Iniciar sesión para comentar.

Categorías

Más información sobre Get Started with MuPAD en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by