Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

How can I make a module that finds the sum of digits of any given positive integer?

I use this command

F[x_]:= Apply[ Plus, IntegerDigits[x] ]

Is there another module to do it ?

share|improve this question
    
Total@IntegerDigits[x] –  Kuba Dec 19 '13 at 23:58
    
Totlal work as plus ?? –  rola Dec 20 '13 at 0:02
    
@rola Look in the Mathematica documentation (F1 button in Mathematica), it is very useful. Total is basically the same as Plus @@ # & which is the same as Apply[Plus, #] &. The main difference, I suppose, is that Total allows you to specify the level (for example you can add up all the elements of a matrix, instead of its rows). –  amr Dec 20 '13 at 0:12
    
@amr thank you.... but when I have to use module or block . I have to use it like g [n_]:=Module [ ] right!! –  rola Dec 20 '13 at 0:22
    
Why do you "have to use Module or Block"? –  Ymareth Dec 20 '13 at 9:58
show 1 more comment

1 Answer

Yes, there are other ways. In Mathematica there are usually many other ways.

Here is a way using DigitCount and Dot:

f1[n_Integer] := DigitCount[n].{1,2,3,4,5,6,7,8,9,0}

f1[2147]
14

It can be easily extended to bases other than 10:

Clear[f1]

f1[n_Integer, b : (_Integer?Positive) : 10] := DigitCount[n, b].Mod[Range[b], b]

In base 7:

f1[2147, 7]
17

Note that there is no need to use Module (or Block), and in fact doing so for concise functions is needless clutter. Module should be used when you need localized Symbols, not merely as cruft to wrap every function you write. Block should be used even more selectively as it temporarily modifies global values. Please see: What are the use cases for different scoping constructs?

Also since I assume you are a new Mathematica user (and even if you're not) I recommend referencing What are the most common pitfalls awaiting new users?.

At some point you may wish to read How to Combine Pattern Constraints and Default Values for Function Arguments for an understanding of the second parameter pattern I used in the extended definition of f1.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.