Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers.

The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips.

Sorting_algorithms/Pancake_sort actually performs the sort some giving the number of flips used. How do these compare with p(n)?

Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16).



References
 Bill Gates and the pancake problem
 A058986


public class Pancake {
    private static int pancake(int n) {
        int gap = 2;
        int sum = 2;
        int adj = -1;
        while (sum < n) {
            adj++;
            gap = 2 * gap - 1;
            sum += gap;
        }
        return n + adj;
    }
 
    public static void main(String[] args) {
        for (int i = 0; i < 4; i++) {
            for (int j = 1; j < 6; j++) {
                int n = 5 * i + j;
                System.out.printf("p(%2d) = %2d  ", n, pancake(n));
            }
            System.out.println();
        }
    }
}