Sum the digits of a number?

103 ビュー (過去 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 Center および File ExchangeGet Started with MuPAD についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by