Ty Scales

Base 4 Repunits

In my previous post I wrote about what primes look like in base 2, and how mersenne primes take on the particular pattern of all 1s. A number in any base consisting of all 1s is called a repunit

1:   1
3:   11
7:   111
31:  1111
127: 1111111

Another interesting pattern to look at in base 2 is alternating 1s and 0s.

5:  101
21: 10101
85: 1010101

A number in this sequence can be generalized as $2^0 + 2^2 + 2^4 … + 2^n$ Where n is the number of 1s in the binary number.


// create a binary number of alternating 1s and 0s
// n=2 == 101
// n=3 == 10101
func OneZeroBinary(n float64) float64 {
    var result float64
	for i := n; i >= 0; i -= 2 {
		result = result + math.Pow(2, i)
	}
	return result
}

There is a simpler way to find the sum for any even number N in the sequence by using the finite geometric series formula.

// for even numbers n
func GeometricSumBase2(n float64) float64 {
    return (math.Pow(4, n/2+1) - 1) / 3
}

Where do base 4 repunits come in to play in all of this? Recall that a repunit is a number consisting of all 1s. Just as we did in base 2, we can represent a number as a sequence. the base 4 number 111 becomes $4^0 + 4^1 + 4^2$. We can write our base 2 sequence in these terms!

$2^0 = 4^0$
$2^2 = 4^1$
$2^4 = 4^2$

and as a geometric series

func GeomtricSumBase4(n float64) float64 {
	return (math.Pow(4, n) - 1) / 3
}
GeometricSumBase2(2)
GeometricSumBase2(4)
GeometricSumBase2(6)
// 5, 21, 85

GeometricSumBase4(2)
GeometricSumBase4(3)
GeometricSumBase4(4)
// 5, 21, 85

In other words, when transforming our base 2 sequence to base 4:
101 becomes 11
10101 becomes 111
1010101 becomes 1111

you can do a similar conversion from base 2 to base 8, just add another zero between 1s

1001 becomes 11
1001001 becomes 111
1001001001 becomes 1111

The sequence is recorded in OEIS as A002450.

#Golang