Hint
Find coordinates (x,y,z) of corresponding values and find the manhattan distance between them. Do all in zero-based instead of one-based indices / numbers.
e.g. input: 6, 12 (1-bases) => 5, 11 (0-based)
value of 5 => (x,y,z) of (2,0,1)
value of 11 => (x,y,z) of (3,1,2)
manhattan dist = abs(2-3) + abs(0-1) + abs(1-2) = 3
more: input: 398 9999 (1-bases) => 397, 9998 (0-based)
(19, 18, 1)
(99, 98, 0)
ans = 161
c++ fragment:
(v = 0-based value)
int u = int(ceil(sqrt(v+1)));
int x = u-1;
int y = -1;
if (v == (x+1)*(x+1)-1) y = x;
...
else