Smallest $k$ Such that $13 + 4 \cdot k \cdot p^2$ is a Perfect Odd Square Given a prime number $p$, I am looking to find the smallest positive integer $k$ such that the following equation $$13 + 4 \cdot k \cdot p^2$$ produces a perfect odd square. All variables are integers. For example, for the prime $43$, $k = 3$. For $p=103$ , it turns out that $k = 1391$. A computer program can solve this for small prime numbers. It is easy to prove that $k$ has to be odd too, which improves the search. But for larger primes, say $p>10^4$, the naive approach of incrementing $k$ untill a suitable value is found just takes a long time.
It is important to mention that not all primes have any solution at all. For those which do have a solution, I am interested in an efficient way for finding it.
Is there any other approach to tackle this? Perhaps one that relates to number theory? Or any other field really which may prove useful.
 A: There is one major optimization screaming at me here.
Check each square sequentially for whether or not it is the “odd square” that the formula equals. This will be faster because $n^2$ (for odd $n$) grows faster than the current linear formula dependent on $k$.
Of course you would start with the first square greater than $13 + 4p^2$ since any lower square is impossible.
This method will be faster when $\frac {n^2}{4p^2} > n - \sqrt{4p^2} = n - 2p$.
I do not know whether or not this equation ever works out to being true. However, for sufficiently large $p$ I strongly suspect that iterating through the squares will be faster.
One may note that my formula assumes that every multiple of $p^2$ needs to be as well as every $n^2$. This cancels out as I would divide both sides by $2$. Therefore it is irrelevant.
EDIT:
I thought about this a bit more. For sufficiently small $k$ iterating through squares will be slower (because the growth rate of sequential squares will be smaller than the growth of sequential multiples of $4p^2$). Once $k > 2p^2 - 1$ the growth of sequential squares outpaces the linear growth of your formula. Therefore you should add something in your code to start counting by squares once you reach $k = 2p^2 - 2$. The value of $n$ to start iterating squares would then be $n = 2p^2 - 1$.
This should be about as fast you can get (assuming $k$ exists) other than iterating through odd values of $k$ and $n$.
