Congettura di Collatz

Vedi la discussione

1

n=int(input("n = "))

lunghezza=1;
while(n != 1):
    lunghezza += 1 # conta un nuovo passo
    if(n%2 == 0):  # se n è pari si divide per 2
        n=n//2
    else:          # se n è dispari...
        n=3*n+1
#----------------------------------------------------
print(lunghezza)

2

Facoltativo: visualizza la sequenza da n a 1, compresi

n=int(input("n = "))
print(n, end=' ')      # Visualizza il numero di partenza

lunghezza=1;
while(n != 1):
    lunghezza += 1 
    if(n%2 == 0):
        n=n//2
    else:
        n=3*n+1
    print(n, end=' ')  # visualizza il risultato dell'algoritmo
#----------------------------------------------------
print()
print(lunghezza)

Versione OII

f=open("input.txt", "r")
n=int(f.read())
f.close()

lunghezza=1;
while(n != 1):
    lunghezza += 1 
    if(n%2 == 0):
        n=n//2
    else:
        n=3*n+1

f=open("output.txt", "w")
f.write(str(lunghezza))
f.close()

Quesito 2

NUM è il numero da 10 a 20 con lunghezza minima LUN

def lunghezza(n):
    conto=1
    while(n != 1):
        conto+=1
        if(n%2 == 0):
            n=n//2
        else: 
            n=3*n+1
    return conto
#----------------------------------------------------
PRIMO =10 
ULTIMO=20 
NUM=0
LUN=1000 # esagerato...

for num in range(PRIMO,ULTIMO+1):
    lun=lunghezza(num)
    if(lun < LUN):
        NUM=num
        LUN=lun
    print(num,lun)  # facoltativo

print(NUM,':',LUN)

matplotlib

La sequenza per n=167

import matplotlib.pyplot as plt
 
n=167
N=[]
N.append(n)
while(n != 1):
    if(n%2 == 0):
        n=n//2
    else: 
        n=3*n+1
    N.append(n)

plt.grid(which="major")
plt.plot(N)
plt.title("Congettura di Collatz, n=167")
plt.show()

Lunghezze per n da 10 a 20

Lunghezze per n da 48 a 52

import matplotlib.pyplot as plt
import math
 
def lunghezza(n): 
    conto=1 
    while(n != 1): 
        if(n%2 == 0): 
            n=n//2 
        else: 
            n=3*n+1 
        conto+=1 
    return conto 

PRIMO =10  # 48
ULTIMO=20  # 52

x=range(PRIMO,ULTIMO+1)
y=[]

NUM=0
LUN=math.inf
for num in x:
    lun=lunghezza(num)
    print(num,lun)
    y.append(lun)
    if(lun < LUN):
        NUM=num
        LUN=lun        

print("-->",NUM,LUN)
    
plt.bar(x,y)
plt.title("Congettura di Collatz, n=10..20")
plt.show()

Da 1 a 100 (1000)

import matplotlib.pyplot as plt
 
def lunghezza(n):
    conto=1
    while(n != 1):
        if(n%2 == 0):
            n=n//2
        else: 
            n=3*n+1
        conto+=1
    return conto

PRIMO =1 
ULTIMO=100               # 1000 
x=range(PRIMO,ULTIMO+1)
y=[]
for n in x:
    lun=lunghezza(n)
    print(n,lun) # facoltativo
    y.append(lun)
    
plt.bar(x,y)
plt.title("Congettura di Collatz, n=" + str(PRIMO) + ".." + str(ULTIMO))
plt.show()