I'm working on coding questions and I want to realize a particular addition (sometimes called "Nim addition")
Here is an example in base 3
Let A=11 and B=21 two numbers written inbase 10.
I want to realize the operation "A plus B" defined this way
- write A and B in base 3 : A -> a=102 and B -> b=210
- do c=a+b just as if a and b were numbers in base 10 : c=312
- compute all digits modulo 3 : 312 -> 012 = 12
- write this number in base 10 : 12 -> 5
Then 11 plus 21 = 5
In Maple"s syntax :
A := 11:
B := 21:
a := convert(A, base, 3): # returns [1, 0, 2]
b := convert(B, base, 3): # returns [0, 1, 2]
# the simplest thing I found to implement operation 2 and 3 above is :
# 1/ convert each list into polynomials (let's say pa and pb)
# 2/ set pc = pa+pb mod 3
# 3/ convert pc into a list
# Instead of coding something like pa := add(a[k]*x^(k-1), k=1..numelems(a)),
# I found more astute to use the gfun package
sa := gfun[listtoseries](a, x, 'ogf'): # returns x^2+2+O(x^3)
sb := gfun[listtoseries](b, x, 'ogf'): # returns 2*x^2+x+O(x^3)
pc := convert(sa, polynom)+convert(sb, polynom) mod 3; # returns x+2
Unfortunately I can't use now gfun[seriestolist](pc, 'revogf') for pc is obviously not a serie !
Reciprocally sc := sa+sb mod 3 doesn't return x+2+O(x^3)
Then I'm trapped here and I don't know how to go further
(of course I know how to proceed if I build directly the polynoms associated to a and b ... but it is far less elegant)
Does anyone have some idea ?
This problems raise the following question: how can we add tho series ?
For instance sa+sb returns (x^2+2+O(x^3))+(2*x^2+x+O(x^3)) without, apparently, no way to simplify this into x+2+O(x^3)
Thanks in advance