This site is supported by donations to The OEIS Foundation.

# User:Joe Slater

Amateur mathematician with an interest in number theory

Some Pari/GP functions:

## A Map() of List()s

Sometimes a function produces the same output value for many input values. I created this wrapper so I could examine each set of inputs for any output:

```   \\ mapoflists takes two arguments, an integer "n"  and a closure "myfun",
\\ and returns a Map() in which each key a number, and each key is associated
\\ with a List() of the input numbers for which the closure produces that output.
\\ E.g.:
\\ ? mapoflists(10,x->x%3)
\\ %1 = Map([0, List([3, 6, 9]); 1, List([1, 4, 7, 10]); 2, List([2, 5, 8])])
mapoflists(n,myfun=(x)->x)=
{
my(m=Map(),output,oldvalue=List());
for(loop=1,n,
output=myfun(loop);
if(!mapisdefined(m,output),
/* then */
oldvalue=List(),
/* else */
oldvalue=mapget(m,output));
listput(oldvalue,loop);
mapput(m,output,oldvalue));
m
}
```

## Binary numbers

bin2dec(n)=fromdigits(n,2) \\ Given a vector of binary numbers, return the decimal integer equivalent

bin_as_dec(n)=fromdigits(binary(n),10) \\ Aesthetic function: given a vector of binary numbers, return the decimal that resembles it

dec_as_bin(n)=my(v=Vec(Str(n)));fromdigits(vector(#v,i,eval(v[i])),2) \\ aesthetic function: return the value of a decimal number or string consisting of 1s and 0s as if it were a binary number

nextbit(n)=my(u=bitand(n, -n), v=u+n); (bitxor(v, n)/u)>>2+v \\ Given a number, return the next number with same binary weight. Copied from Charles R Greathouse IV 

## Collatz Conjecture

terras(n)=(n+n%2*(2*n+1))/(2) \\ Reduced Collatz function

trajectory(n=1)=if(n==1,[n],concat(trajectory(terras(n)),[n])) \\Vector of intermediate numbers in reduced Collatz trajectory from n to 1

height(n)=#trajectory(n)-1 \\ Number of n/2 steps in repeated Collatz applications until n=1; same as OEIS A006666

breadth(n)=hammingweight(fromdigits(parityvector(trajectory(n)),2))-1 \\ Number of tripling steps to reach 1 in '3x+1' problem; same as A006667

## Misc

parityvector(n)=vector(#n,x,n[x]%2) \\ Given a vector, return a new one with 1 for odd values and 0 for even ones