Skip to content

Instantly share code, notes, and snippets.

@joriki
Created December 30, 2019 06:36
Show Gist options
  • Save joriki/ae7cc5409cf2263e283517b24a6d2ca7 to your computer and use it in GitHub Desktop.
Save joriki/ae7cc5409cf2263e283517b24a6d2ca7 to your computer and use it in GitHub Desktop.
Find the cycle lengths of the permutation represented by the triangular numbers modulo powers of two; see https://math.stackexchange.com/questions/3491781.
package temp;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class Question3491781 {
public static void main(String [] args) {
for (int n = 4;;n <<= 1) {
BitSet bitSet = new BitSet(n);
List<Integer> cycleLengths = new ArrayList<Integer>();
outer:
for (;;) {
int k = 0;
while (bitSet.get(k))
if (++k == n)
break outer;
int cycleLength = 0;
int first = k;
do {
bitSet.set(k);
k = ((k * (k + 1)) / 2) & (n - 1);
cycleLength++;
} while (first != k);
cycleLengths.add(cycleLength);
}
Collections.sort(cycleLengths);
cycleLengths.remove(0);
cycleLengths.remove(0);
Collections.reverse(cycleLengths);
System.out.println(" " + n + " : " + cycleLengths.stream().map(i -> i.toString()).collect(Collectors.joining(", ")));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment