Skip to content

Instantly share code, notes, and snippets.

@christian-mann
Created February 7, 2020 17:51
Show Gist options
  • Save christian-mann/74a6996c159347b53c9664cb9c8230fa to your computer and use it in GitHub Desktop.
Save christian-mann/74a6996c159347b53c9664cb9c8230fa to your computer and use it in GitHub Desktop.
Collatz-like thing (Python 3)
import sys
import math
def factors(n):
while n % 2 == 0:
yield 2
n //= 2
for i in range(3, int(math.sqrt(n))+1, 2):
while n % i == 0:
yield i
n //= i
if n > 2:
yield n
def printfactors(n):
count = 0
factor = 0
s = ""
for p in factors(n):
if p == factor:
count += 1
else:
if factor:
s += "%3d^%2d " % (factor, count)
factor = p
count = 1
if factor:
s += "%3d^%2d " % (factor, count)
return s
def highestprimefactor(n):
return max(factors(n))
def iterate(n):
p = highestprimefactor(n)
if n == p: return None
return n + p - 1
def getcount(n, thresh=100):
m = n
count = 0
while m and count < thresh:
m = iterate(m)
count += 1
if m:
return 'INF'
else:
return count
if __name__ == "__main__":
for n in range(10, 10000, 2):
count = getcount(n)
if count != 'INF':
print(n, count, ' ', ' '.join(map(str, factors(n))))
#n = int(sys.argv[1])
#while n:
# print (n, ' '.join(map(str, factors(n))))
@christian-mann
Copy link
Author

christian-mann commented Feb 7, 2020

All odd numbers appear to terminate; some of the first terminating even numbers:

Number Iterations Factors
16 2   2 2 2 2
22 4   2 11
32 3   2 2 2 2 2
52 7   2 2 13
58 9   2 29
60 7   2 2 3 5
64 6   2 2 2 2 2 2
86 8   2 43
128 7   2 2 2 2 2 2 2
226 13   2 113
256 2   2 2 2 2 2 2 2 2
268 13   2 2 67
282 14   2 3 47
310 12   2 5 31
328 13   2 2 2 41
330 12   2 3 5 11
334 12   2 167
338 12   2 13 13
340 11   2 2 5 17
350 11   2 5 5 7
356 10   2 2 89
366 11   2 3 61
368 12   2 2 2 2 23
372 11   2 2 3 31
374 12   2 11 17
388 8   2 2 97
390 11   2 3 5 13
400 12   2 2 2 2 5 5
402 10   2 3 67
404 11   2 2 101
420 11   2 2 3 5 7
426 10   2 3 71
438 10   2 3 73
444 9   2 2 3 37
468 9   2 2 3 3 13
480 8   2 2 2 2 2 3 5
484 7   2 2 11 11
490 10   2 5 7 7
494 6   2 13 19
496 9   2 2 2 2 31
500 11   2 2 5 5 5
504 10   2 2 2 3 3 7
510 9   2 3 5 17
512 5   2 2 2 2 2 2 2 2 2
526 8   2 263
646 25   2 17 19
664 24   2 2 2 83
708 23   2 2 3 59
746 23   2 373
766 22   2 383
788 7   2 2 197
984 6   2 2 2 3 41

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment