Sum of Digits

1 vue (au cours des 30 derniers jours)
joseph Frank
joseph Frank le 16 Avr 2011
Hi,
If I have the following vector: [1 9 11 3 7 8 14] then how can I add the double digits (when the number is greater than 9)to get a single digit? i.e. to get: [1 9 2 3 7 8 5]

Réponse acceptée

Paulo Silva
Paulo Silva le 16 Avr 2011
a=[1 9 11 3 7 8 14]
a(a>9)=a(a>9)-9
Edit: Like John said the code fails for numbers bigger than 18 and we can repeat the process, the following code works for every number but it will be slow for bigger values and vectors.
while max(a)>9
a(a>9)=a(a>9)-9
end
  2 commentaires
John D'Errico
John D'Errico le 16 Avr 2011
While this does work for numbers no larger than 18, it will fail for all larger values! The answer suggested does not compute the sum of the digits. It merely subtracts 9 from the number. For example, 22 will map to 13, which is still greater than 1. Yes, you can repeat the operation until the result is no larger than 9, but that seems a bit of a kludge, since it will take a long time for termination if a single element was as large as perhaps 123432455243.
Paulo Silva
Paulo Silva le 16 Avr 2011
nice point John, I just tried to find the simplest way to satisfy the example provided

Connectez-vous pour commenter.

Plus de réponses (1)

John D'Errico
John D'Errico le 16 Avr 2011
A few better solution than Paulo's is to use modular arithmetic. This is because Paulo's solution fails for inputs larger than 18. Yes, you could simply repeat that process, but it would get time consuming if the element was 34343454356. In effect, you are performing division by repeated subtraction, a VERY slow operation for large inputs.
Instead, reduce your vector modulo 9, replacing any elements which got mapped to zero, with a 9.
vector = [1 9 11 3 7 8 14 197 90];
newvector = mod(vector,9);
newvector(newvector == 0) = 9;
In the event that any element in the original vector was already a 0, you may choose not to convert that 0 element to a 9. This would be a simple modification to the above code, so perhaps you would have done it as...
vector = [1 9 11 3 7 8 14 197 90];
newvector = mod(vector,9);
newvector((newvector == 0) & (vector ~= 0)) = 9;
  1 commentaire
Paulo Silva
Paulo Silva le 16 Avr 2011
+1 vote

Connectez-vous pour commenter.

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by