fkampas
(Frank Kampas)
September 23, 2016, 5:30pm
1
Casting out nines is a way to check ones arithemetic using module mathematics since the value of a number modulo 9 can be calculated by repeated summing the digits and then setting 9 equal to 0.
In[1]:= cnine[n_Integer] :=
FixedPoint[Total[IntegerDigits[#]] &, n] /. 9 -> 0
In[2]:= Mod[Range[1000], 9] == cnine /@ Range[1000]
Out[2]= True
Casting out elevens is tricker, since the repeated operation is alternatedly adding and subtracting the digits, starting from the right and adding 11 if the result is negative.
In[3]:= t[l_List] :=
If[# < 0, # + 11, #] & @
Total[(-1)^Range[0, Length[l] - 1]*Reverse[l]]
In[4]:= celev[n_Integer] := FixedPoint[t[IntegerDigits[#]] &, n]
In[5]:= Mod[Range[1000], 11] == celev /@ Range[1000]
Out[5]= True
Perhaps someone can produce a more elegant implementation.
mhelmle
(Michael Helmle)
September 24, 2016, 3:53pm
2
What about using a base 12 system?
celeven[n_Integer] :=
FixedPoint[Total[IntegerDigits[#, 12]] &, n] /. 11 -> 0
Mod[Range[1000], 11] == celeven /@ Range[1000]
1 Like
fkampas
(Frank Kampas)
September 24, 2016, 4:40pm
4
I didn’t test my approach to high enough numbers. The addition of 11 needs to be done between each addition or subtraction.
My corrected code is
In[1]:= p[n1_, n2_] := If[n1 + n2 < 0, n1 + n2 + 11, n1 + n2]
In[2]:= s[l_List] := Fold[p, First[l], Rest[l]]
In[3]:= t[l_List] := s[(-1)^Range[0, Length[l] - 1]*Reverse[l]]
In[4]:= c11[n_Integer] := FixedPoint[t[IntegerDigits[#]] &, n]
In[5]:= Mod[Range[10^5], 11] == c11 /@ Range[10^5]
Out[5]= True
jvenezian
(Jonathan Venezian)
December 12, 2021, 11:21am
5
Or you can recurse the function, 20202020202 outputs 12, 12 outputs 1