Python Forum
How can I found how many numbers are there in a Collatz Sequence that I found?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can I found how many numbers are there in a Collatz Sequence that I found?
#1
I tried to find the longest starting value less than 100,000 in a Collatz Sequence. Actually, I have two questions:

1)Output is 77,031, is this correct?
2)How can I find how many elements are there in the sequence that I found?

def sequence_number(n):
term = 1
while n > 1:
    if n % 2 == 0:
        n = n/2
    else:
        n = 3 * n+1
    term += 1
return term
 
def starting_number():
t = 0
x = 1
while x < 100000:
    if sequence_number(x) > t:
        t = sequence_number(x)
        value = x
    x += 1
 
return value
 
print("It starts with the number:", starting_number())
Reply
#2
Hi i see some potential issues:
- Indentation in the functions cannot be right
-you seem to be returning (line17) the value, rather than t.

Tell us what the max sequence is. Less than 77031 ?

Paul
Reply
#3
The result seems to be right. Just your indentation is wrong. For infinite sequences (collatz is one of them) Generators could be used.

Here is a derivation of your code:
from itertools import count


def ask_int(question):
    while True:
        user_input = input(question + ": ")
        try:
            return int(user_input)
        except ValueError:
            print(f"'{user_input}' is not a valid integer")


def collatz_generator(start):
    if start < 1:
        raise ValueError("Start must be a positive integer")
    n = start
    while n > 1:
        if n % 2 == 0:
            n = n // 2
        else:
            n = 3 * n + 1
        yield n


def collatz_counter(start):
    if start < 1:
        raise ValueError("Start must be a positive integer")
    n = start
    for trys in count(1):
        if n % 2 == 0:
            n = n // 2
        else:
            n = 3 * n + 1
        if n <= 1:
            break
    return trys


def longest_collatz(start=1, end=100_000):
    maximum_length = 0
    maximum_value = 0
    for value in range(start, end + 1):
        length = collatz_counter(value)
        if length > maximum_length:
            maximum_length = length
            maximum_value = value
    return maximum_value, maximum_length


if __name__ == "__main__":
    print("Find the longest collatz sequence with given start and end")
    start = ask_int("Start Value")
    end = ask_int("End Value")
    value, length = longest_collatz(start, end)
    print(f"The start value {value} creates a collatz sequence with {length} values.")
Quote:PS C:\Users\Admin\Desktop> py collatz.py
Find the longest collatz sequence with given start and end
Start Value: 1
End Value: 100_000
The start value 77031 creates a collatz sequence with 350 values.
PS C:\Users\Admin\Desktop> py collatz.py
Find the longest collatz sequence with given start and end
Start Value: 1
End Value: 1_000_000
The start value 837799 creates a collatz sequence with 524 values.

I think the code is also a bit faster.
The generator collatz_generator is not used in the code. I didn't remove it. Maybe you can experiment with it.

gen = collatz_generator(19)
print(list(gen))
In [1]: gen = collatz_generator(19)
   ...: print(list(gen))
[58, 29, 88, 44, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
The 19 is not included. My mistake. Quick fix just for completeness:

def collatz_generator(start):
    if start < 1:
        raise ValueError("Start must be a positive integer")
    n = start
    yield n # <-- this will yield n, which is the start value
    while n > 1:
        if n % 2 == 0:
            n = n // 2
        else:
            n = 3 * n + 1
        yield n # <-- this here are the values after the start value
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#4
@DeaD_EyE:
I thought we were looking for the most iterations,
but we are looking for the value that causes them, indeed 77031!
Paul
Reply
#5
Quote:The start value 77031 creates a collatz sequence with 350 values.

Yes, we're looking for the most iterations (sequence length).
Given is start value from 1 to 100_000 for example.
Calculate for each start value, the collatz sequence length.
Take the longest sequence and tell us the start value.

In collatz_counter I count the iterations (hopefully right).
In longest_collatz I calculate the maximum_length (sequence length / iterations) and the corresponding start value to get this maximum length.


By the way, negative values are also possible for a collatz sequence. In this case the addition of 1 changed to subtraction.
Just for completeness:

def collatz_generator(start):
    n = start
    if n < 0:
        offset = -1
    else:
        offset = +1
    yield start
    while abs(n) > 1:
        if n % 2 == 0:
            n = n // 2
        else:
            n = 3 * n + offset
        yield n
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#6
(Nov-19-2020, 09:20 AM)DPaul Wrote: @DeaD_EyE:
I thought we were looking for the most iterations,
but we are looking for the value that causes them, indeed 77031!
Paul

I really appreciate your help!! Thank you so much
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Random Generator: From Word to Numbers, from Numbers to n possibles Words Yamiyozx 2 1,427 Jan-02-2023, 05:08 PM
Last Post: deanhystad
Exclamation Homework( Solution found) Zaochen 2 1,842 Dec-23-2021, 04:18 PM
Last Post: BashBedlam
  Collatz-problem CaptainNeemo 2 2,209 Dec-07-2020, 04:09 PM
Last Post: deanhystad
  Convert list of numbers to string of numbers kam_uk 5 3,016 Nov-21-2020, 03:10 PM
Last Post: deanhystad
  Printing sequence of numbers kam_uk 1 2,839 Sep-27-2020, 01:50 PM
Last Post: perfringo
  How to update set of hash values until final hash value is found using the 5 hashes shakespeareeee 1 1,972 Jul-25-2019, 12:34 AM
Last Post: Larz60+
  [split] The Collatz Sequence valencia 4 3,697 Jan-06-2019, 08:10 PM
Last Post: valencia
  The Collatz Sequence Truman 11 14,113 Dec-27-2018, 11:28 PM
Last Post: Truman
  Trying to teach myself how to code and I'm stuck on a question I found online... abushaa4 1 2,210 Dec-16-2018, 01:52 PM
Last Post: ichabod801
  Dataload() crash when filename is not found Mark3232 1 1,929 Dec-08-2018, 10:23 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020