I have this tiny program for finding largest prime divisor (taken from Code Review Stackexchange and written by user Altinak: https://codereview.stackexchange.com/a/74792):
Here is my try to write it in pseudocode:
GLOBAL VARIABLE highest;
// This function takes parameters n and f with 1 <= n and 2 <= f.
// It returns n with f factored out of it.
// Also, if f divides n and if f > h then it replaces h with f
factorize(n, f) {
if (n < f)
return n
while (n mod f == 0) {
n = n / f
if (f > highest)
highest = f
}
return n
}
find(n) {
highest = 1
n = factorize(n, 2)
n = factorize(n, 3)
if (n >= 5) {
i = 5
while (i * i <= n) {
n = factorize(n, i)
n = factorize(n, i + 2)
i = i + 6
}
}
if (n == 1)
return highest
else
return n
}
But the while
loop in the function find
is harder than ones I have seen before - its number of iterations aren't easy to calculate before the loop, as the variable n
from the condition i * i <= n
changes in the loop body.
Right now I feel like I'm stuck and have no idea how to write the loop invariant for this loop, but I will try to think of something. Meanwhile, big thanks in advance for any hints!
factorize()
. $\endgroup$factorize()
takes parametersn
andf
with1 <= n
and2 <= f
. It returnsn
withf
factored out of it, and also, iff
dividesn
and iff > h
then it replacesh
withf
. Smth like this. Should I add it to the post? $\endgroup$