/* * Run 'a.out #N' to show, iteratively, the sum of factors of N. * Perfect numbers will have cycle 1, amicable cycle 2, etc. * * Note the efficient caulculation of sum of factors. */ #include typedef unsigned long long Number; Number findfact(Number x) { Number y; if (x % 2 == 0) return 2; if (x % 3 == 0) return 3; if (x % 5 == 0) return 5; for (y = 6; y * y < x; y += 6) { if (x % (y + 1) == 0) return y + 1; if (x % (y + 5) == 0) return y + 5; } return x; } Number fsum(Number x) { Number y, sum, res, ff, prm; int nf; prm = sum = res = ff = 1; while (1) { y = findfact(x); if (y != prm) { sum *= res; prm = y; res = ff = 1; } if (y < 2) return sum; res += (ff *= prm); x /= y; } } int main(int argc, char **argv) { long long m, x; setbuf(stdout, 0); m = x = argc > 1 ? atol(argv[1]) : 30114860L; printf("%Ld -> ", x); while (x > 1) { x = fsum(x) - x; printf("%Lu -> ", x); if (x < m) m = x; else if (x == m || x == 14316) break; } printf("\n"); return 0; }