Comment by Someone
3 days ago
> If you wanted a c++26 preconditon for collatz tho, here it is.
cpp bool collatz(unsigned long long n)
{
while (n != 1)
n = n % 2 ? 3 * n + 1 : n / 2;
return true;
}
You’ll need to add code to detect cycles other than 1, 4, 2, 1, 4, 2,… to that. That can be done in constant space (https://en.wikipedia.org/wiki/Cycle_detection#Floyd’s_tortoi...)
Ideally, you also need a way to detect runs towards infinity. That is harder.
Otherwise, an optimising compiler can use the forward progress guarantee and optimize that to:
cpp bool collatz(unsigned long long n)
{
return true;
}
and then completely remove the precondition.
I think I saw years ago that clang replaced a collatz impl with true. Why is it that the "forward progress garuntee" would let it do that?
You may think about this blog post from John Regehr about Fermat's Last Theorem: https://blog.regehr.org/archives/140
Thanks! Great read, and makes good sense.
For future readers his sequel post explains the specific cause.
https://blog.regehr.org/archives/161