/* This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * Find a number in a given range that has the longest Collatz sequence. * http://en.wikipedia.org/wiki/Collatz_conjecture * */ { int low, high; int winner, winnerlen; int cur, curlen; int i; low = 2; // invariant: low > 1 high = 4096; winner = low; winnerlen = 1; for (i = low; i <= high; i ++){ cur = i; curlen = 1; while (cur != 1){ if (cur % 2 == 0) cur /= 2; else cur = 3 * cur + 1; ++ curlen; } if (curlen > winnerlen) winner = i, winnerlen = curlen; } writeint winner; while (winner != 1) { if (winner % 2 == 0) winner /= 2; else winner = 3 * winner + 1; writeint winner; } writeint winnerlen; }