Skip to content

Step-By-Step Collatz Sequence #2843 #2845

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

BhavanKumarGM
Copy link

🔹 Collatz Sequence Problem

The Collatz sequence (also called the 3n + 1 problem) is a simple mathematical process:
1. Start with any positive integer n.
2. If n is even, divide it by 2 → n = n / 2.
3. If n is odd, multiply it by 3 and add 1 → n = 3n + 1.
4. Repeat this process with the new value of n.
5. Eventually (for all tested numbers), the sequence will reach 1.

Explaining the code part:
Description
When the user enters a non-integer (like "abc"), the program raises a ValueError and exits immediately. It would be better if the program handled this by showing an error message and requesting valid input again.

**Steps to reproduce**  
          1. Run the program (e.g., in Python).  
          2. Input “abc” instead of a number.

 **Expected behavior**  
          Program prints something like “Please enter a valid positive integer.” and then prompts again.

 **Actual behavior**  
          Program crashes with a traceback, e.g., `ValueError: invalid literal for int() with base 10: 'abc'`.

 **Suggested fix**  
          Wrap the input logic in a loop with `try/except`, and use `continue` in the except block to reprompt.

 **The Main Function**
             while True:
                       try:
                            num = int(input("Enter a positive integer: "))
                             if num > 0:
                                   break
                             else:
                                  print("Please enter a positive integer.")
                       except ValueError:
                                 print("Invalid input! Please enter a number.")
                                 continue
 **Conclusion** 
             This approach ensures the program doesn't crash on bad input and prompts the user again in a friendly way.

@BhavanKumarGM BhavanKumarGM changed the title Step-By-Step Collatz Sequence Step-By-Step Collatz Sequence #8543 Aug 18, 2025
@BhavanKumarGM BhavanKumarGM changed the title Step-By-Step Collatz Sequence #8543 Step-By-Step Collatz Sequence #2843 Aug 18, 2025
@BhavanKumarGM
Copy link
Author

Kindly review this and let me know if any modifications are required.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant