q = p/2 if p is even, q = (p+3)/2 if p is odd.
p is the perimeter.
Let us say p = 35, then q = (35+3)/2 = 19 = 6 *3 + 1 (here k is 3)
If p = 34, then q = 34/2 = 17 = 6 *2 + 5 (here k is 2).
The key point is to write q as a multiple of 6 with a remainder (this remainder can be zero if q is divisible by 6). k value is not used in the calculation.
Hope this will help.