Prime Caves
Time limit1sMemory limit128 MB
Starting from cave n on a spiral-numbered grid, descend down-left, down, or down-right to collect the most prime-numbered caves.
- Level
Medium6 of 10
- Topics
- Dynamic programming, Number theory, Math
- Solved
- No attempts yet
Problem
An international expedition found abandoned Buddhist cave temples in a giant cliff that stands in the middle of a desert. Small caves were dug halfway down the vertical rock face, and their entrances line up on a square grid. The archaeologists on the team were excited by the Buddha statues inside. Some caves also hid scrolls of Buddhist sutras. Those scrolls are estimated to be more than a thousand years old, and their value cannot be measured.
The leader of the expedition wants to collect as many scrolls as possible. Getting into a cave is hard, because the caves sit halfway down the cliff. The only way in is to hang from a helicopter. Once you have entered a cave and explored it, you can climb down into one of three caves: the cave directly below, the cave to the left of the one directly below, or the cave to the right of it. You can repeat this move as many times as you want, and then you go down to the ground on a long rope.
So one attempt covers several caves. Which caves should you visit? A mathematician on the team studied the preliminary attempts and found two facts. First, the caves can be numbered from the central one, spiraling outward as in Figure 1. Cave 1 sits at the center, cave 2 is immediately to its right, cave 3 is above cave 2, and the numbering winds counterclockwise from there. Second, only the caves whose number is prime store scrolls. Such caves are called prime caves, and they are circled in the figure.

Figure 1: numbering of the caves and the prime caves
Given the total number of caves and the cave you enter first, write a program that finds the descending route containing the largest number of prime caves.
Input
The input consists of several datasets. Each dataset is one line holding an integer () and an integer (), separated by a space. is the total number of caves, and is the number of the cave where the exploration starts. The line after the last dataset holds two zeros.
Output
For each dataset, find the route that starts at cave and contains the largest number of prime caves. Print the number of prime caves on that route and the number of the last prime cave on it, on one line, separated by a space. Cave , explored first, counts as part of the route. If several routes reach that largest number, report the one whose last prime cave has the largest number. If no route reaches a prime cave at all, print 0 0.