In what concerns the continuous evaluation solving exercises grade during the semester, you should submit until 23:59 of November 23rd
(this exercise will still be available for submission after that deadline, but without counting towards your grade)
[to understand the context of this problem, you should read the class #06 exercise sheet]


In this problem you should submit a function as described. Inside the function do not print anything that was not asked!

[IP062] Treasure Hunt

One dark and stormy evening at the Springfield Nuclear Power Plant, Mr. Burns, the town’s wealthiest (and most eccentric) resident, sits in his luxurious office, poring over an ancient map, encoded in the form of an infinite spiral matrix, with numbers arranged in rows and columns. Here are the first five layers of the spiral, starting on cell (1,1):

Legend has it that certain positions on this grid could lead to unimaginable wealth - or so Mr. Burns believes. The problem is that the map's instructions require a very specific number from seemingly random (y, x) coordinates on the grid. And Mr. Burns, not one for patience, wants instant access to these values without having to search row by row.

The Problem

Write a function spiral_number(y, x) that receives a pair of coordinates (y, x) and returns the number at that position in the infinite spiral matrix shown above.

Constraints

The following limits are guaranteed in all the test cases that will be given to your program:

1 ≤ y, x ≤ 109       Coordinates of the number

NOTE: the limits are really high and you must have an efficient solution that can compute this very quickly.
A solution that simply tries to simulate the spiral number by number will most likely have Time Limit Exceeded.
Your program will need to be able to answer around five hundred queries in less than one second.


Example Function Calls Example Output
print(spiral_number(2,3))
print(spiral_number(1,1))
print(spiral_number(4,2))
print(spiral_number(170550340,943050741))
8
1
15
889344699930098742

Introduction to Programming (CC1024)
DCC/FCUP - University of Porto