Sum the digits of a number?

조회 수: 115 (최근 30일)
tzenh karetzh
tzenh karetzh 2014년 1월 17일
이동: Dyuman Joshi 2023년 9월 18일
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
José-Luis
José-Luis 2014년 1월 17일
Is this homework?
tzenh karetzh
tzenh karetzh 2014년 1월 17일
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

댓글을 달려면 로그인하십시오.

답변 (7개)

Les Beckham
Les Beckham 2020년 5월 2일
편집: Les Beckham 2020년 5월 2일
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
Dimitri
Dimitri 2021년 4월 6일
This won't work...mod(45,9) give zero..but what he wants is 9.
John D'Errico
John D'Errico 2021년 4월 6일
@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

댓글을 달려면 로그인하십시오.


Azzi Abdelmalek
Azzi Abdelmalek 2014년 1월 17일
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
rohan dhane
rohan dhane 2019년 11월 15일
you are fanta.......
Stephen23
Stephen23 2019년 11월 15일
편집: Stephen23 2019년 11월 15일
Simpler without regexp and str2double:
a = 525;
b = num2str(a);
while numel(b)>1
a = sum(b-'0');
b = num2str(a);
end
out = a;

댓글을 달려면 로그인하십시오.


Sean de Wolski
Sean de Wolski 2014년 1월 17일

Ans sadiq
Ans sadiq 2021년 8월 19일
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 2019년 2월 5일
You can try this:
n = 525;
sum(str2num(num2str(sum(str2num(num2str(n)')))'))
  댓글 수: 4
Stephen23
Stephen23 2019년 2월 6일
편집: Stephen23 2019년 2월 6일
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 2019년 2월 6일
Well seen! Thank you for your observation.

댓글을 달려면 로그인하십시오.


Image Analyst
Image Analyst 2021년 4월 7일
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 2023년 9월 15일
편집: Javier Echanobe 2023년 9월 15일
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
Dyuman Joshi
Dyuman Joshi 2023년 9월 15일
@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 2023년 9월 18일
이동: Dyuman Joshi 2023년 9월 18일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Get Started with MuPAD에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by