Project Euler 622 - Riffle Shuffles

Official link: https://projecteuler.net/problem=622

Thought Process

For some reason, the "Riffle shuffle" in question is actually known as the Faro Shuffle, specifically, we are talking about a faro out-shuffle.

From the Wiki we get the following:

Take finding all s(n) = 8 as an example:

The sum of all n such that s(n) = 8 is all n such that 2^8 = 1 (mod n - 1) and 8 is the smallest number to do this

First notice that: 2^8 = 1 (mod n - 1) => 2^8 - 1 = (n - 1)*l => 255 = (n - 1)*l

We now have our candidate n's. Find the Divisors of 255, they are [1, 3, 5, 15, 17, 51, 85, 255]

For each candidate number, x,

  1. first we check if 2^8 (mod x) = 1

    1. If this is true, we need to check if it is the smallest. To do this we know that if there is a smaller number it has to be a divisor of 8 (Think about why)

      1. If it is the smallest add x + 1 to a total

In this example the numbers [17, 51, 85, 255] satisfy the conditions, hence in total (including the +1) we get 412 as desired. I repeated the process for 60 exactly the same, took around ~95s to get the answer.

Interactive Code

Input an integer (yourinput)

Code will output the sum of all n such that s(n) = yourinput