puzzle contents
Contents
raw puzzle

Codingame Solution: Rubik

Robert Eisele

Original Problem

A Rubik's Cube® is a cube composed of several mini-cubes which pivot around the center along 3 axes.

Your program must output the number of mini-cubes visible on a cube of the given size.
INPUT:
N an integer.

OUTPUT:
An integer for the number of mini-cubes visible on a NxNxN Rubik's Cube®.

CONSTRAINTS:
0 < N < 100

Solution

The top and bottom layer is formed by \(2n^2\) cubes. The four sites can also by calculated the same way but reduced by the corner cubes, leading to \(4(n-2)^2\). Now the corners must be added again, which are \(4(n-2)\). In total, this leads to \(2n^2+4(n-2)^2+4(n-2)\).

\[\begin{array}{rl} f(n) &= 2n^2+4(n-2)^2+4(n-2)\\ &= n \cdot (6 n - 12) + 8 \end{array}\]

This doesn't work for \(f(1)=2\), since a cube formed of one small cube should be one. Another way to think about the problem is calculating the volume of the cube and reducing it by the volume of the inner cube, which leads to the same solution:

\[\begin{array}{rl} f(n) &= n^3 - (n-2)^3\\ &= n \cdot (6 n - 12) + 8 \end{array}\]

Interesting enough, when we factor the function to be

\[\begin{array}{rl} f(n) &= n \cdot (6 n - 12) + 8\\ &= 6 \cdot (n-1) (n-1) + 2 \end{array}\]

we arrive at the well known OEIS sequence A005897. Implementing this function is then quite trivial. Here in Java:

import java.util.*;

class Solution {

    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int N = in.nextInt() - 1;

        if (N == 0)
            System.out.println(1);
        else
            System.out.println(6 * N * N + 2);
    }
}