### Cyclical figurate numbers题号：61 难度： 20 中英对照

Triangle, square, pentagonal, hexagonal, heptagonal, and octagonal numbers are all figurate (polygonal) numbers and are generated by the following formulae:

 Triangle P3,n=n(n+1)/2 1, 3, 6, 10, 15, ... Square P4,n=n2 1, 4, 9, 16, 25, ... Pentagonal P5,n=n(3n−1)/2 1, 5, 12, 22, 35, ... Hexagonal P6,n=n(2n−1) 1, 6, 15, 28, 45, ... Heptagonal P7,n=n(5n−3)/2 1, 7, 18, 34, 55, ... Octagonal P8,n=n(3n−2) 1, 8, 21, 40, 65, ...

The ordered set of three 4-digit numbers: 8128, 2882, 8281, has three interesting properties.

1. The set is cyclic, in that the last two digits of each number is the first two digits of the next number (including the last number with the first).
2. Each polygonal type: triangle (P3,127=8128), square (P4,91=8281), and pentagonal (P5,44=2882), is represented by a different number in the set.
3. This is the only set of 4-digit numbers with this property.

Find the sum of the only ordered set of six cyclic 4-digit numbers for which each polygonal type: triangle, square, pentagonal, hexagonal, heptagonal, and octagonal, is represented by a different number in the set.

### Code

import java.util.HashSet;
import java.util.Set;

public final class p61{

public static void main(String[] args) {
long start = System.nanoTime();
int result = run();
long end = System.nanoTime();
System.out.println( result );
System.out.println (( end - start )/1000000 +"ms");
}

// numbers[i][j]保存一系列多边形数，i表示边数3 <= i <=8 ）,是4位数，前两位的数值等于j
private static Set<Integer>[][] numbers;

public static int run() {
//得到4位的多边形数，放入number数组中
numbers = new Set;
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers[i].length; j++)
numbers[i][j] = new HashSet<>();
}
for (int sides = 3; sides <= 8; sides++) {
for (int n = 1; ; n++) {
int num = figurateNumber(sides, n);
//多边形数大小为4位
if (num >= 10000)
break;
if (num >= 1000)
numbers[sides][num / 100].add(num); //j等于多边形数的前两位
}
}

// 寻找满足条件的多边形数
for (int i = 10; i < 100; i++) { //number的第二个参数不大于100
for (int num : numbers[i]) {
int temp = findSolutionSum(num, num, 1 << 3, num);
if (temp != -1)
return temp;
}
}
throw new AssertionError("No solution");
}

//4个参数分别为代表
private static int findSolutionSum(int begin, int current, int sidesUsed, int sum) {
//sideUsed表示已取到的多边形数，0x1F8=111111000的前八位为1表示三、四、...、八多边形数已经都取到了
if (sidesUsed == 0x1F8) {
//最后一个数的后两位也是第一个数的前两位，则这几个数字的和
if (current % 100 == begin / 100)
return sum;

} else {
for (int sides = 4; sides <= 8; sides++) {
if (((sidesUsed >>> sides) & 1) != 0)
continue;
for (int num : numbers[sides][current % 100]) {
int temp = findSolutionSum(begin, num, sidesUsed | (1 << sides), sum + num);
if (temp != -1)
return temp;
}
}
}
return -1;
}

//多边形数公式
private static int figurateNumber(int sides, int n) {
return n * ((sides - 2) * n - (sides - 4)) / 2;
}
}
28684
5ms