Calvin H
Calvin H

Reputation: 11

Collatz Conjecture multiple divisors

Is there a way we can have multiple divisors? For example like this: collatz(30,[2,3,5],6,1,maxSize=64). Where we can choose what kind of divisors we want to put in.
My code currently gives me an error saying "TypeError: unsupported operand type(s) for %: 'int' and 'list'" and I have no idea how to fix this mess. Please help! Thank you~~

import numpy as np

def collatz(n,divs=2,mult=3,inc=1,maxSize=-1):
    result = []
    
    while n not in result and len(result)!=maxSize:
        result.append(n)
        n =  (n*mult+inc)if n%divs else np.divide(n//divs)
    return result + ['stop']*(n not in result)

collatz(30,[2,3],6,1,maxSize=64)

Upvotes: 0

Views: 73

Answers (1)

Guinther Kovalski
Guinther Kovalski

Reputation: 1919

when you do:

if n%divs

you can have ambiguity since it can be true and false, so you have to decide what is the logic to be used here if [1,1],[1,0],[0,1],[0,0].

You can convert both to np.arrays and use np.mod:

https://numpy.org/doc/stable/reference/generated/numpy.mod.html

I guess that you want to use a different definition than the collatz one, simultaneously, so i made a small change, see if it works:

import numpy as np

def collatz(n):
    n = n/2 if n%2==0 else 3*n+1
    return n

def different_collatz(n):
    n = n/2 if n%3==0 else 3*n+1
    return n

def search(n,divs=2,mult=3,inc=1,maxSize=-1):
    result = []
    k = n
    while (n not in result) or (k not in result)  and len(result)!=maxSize:
        result.append(n)
        n = collatz(n)
        k = different_collatz(k)

        result.append(k)
    return result + ['stop']*(n not in result)

result = search(30,[2,3],6,1,maxSize=64)
print(result)

result:

[30, 15]

Upvotes: 1

Related Questions