File tree Expand file tree Collapse file tree 1 file changed +18
-24
lines changed Expand file tree Collapse file tree 1 file changed +18
-24
lines changed Original file line number Diff line number Diff line change 1
- def collatz_steps (n ):
2
- times = 0
1
+ def collatz_sequence (n ):
2
+ """Generate and print the Collatz sequence for n."""
3
+ steps = [n ]
3
4
while n != 1 :
4
5
if n % 2 == 0 :
5
- print (f"{ n } / 2" , end = " " )
6
- n = n // 2 # "//" is a floor division where it rounds down the result
6
+ n = n // 2
7
7
else :
8
- print (f"{ n } * 3 + 1" , end = " " )
9
8
n = 3 * n + 1
10
- print (f"= { n } " )
11
- times += 1
12
- print (f"The number of times to reach 1 is { times } " )
9
+ steps .append (n )
10
+ return steps
13
11
14
- def main ():
15
- again = "y"
16
- while again != "n" :
17
- n = int (input ("Input a number: " ))
18
- collatz_steps (n )
19
- while True :
20
- again = str (input ("Want to input again? y/n: " ))
21
- if again != "n" and again != "y" :
22
- print ("Incorrect Input." )
23
- elif again == "n" :
24
- print ("Thank You! Goodbye." )
25
- break
26
- else :
27
- break
28
-
29
- main ()
12
+ # --- Main Program ---
13
+ try :
14
+ num = int (input ("Enter a positive integer: " ))
15
+ if num <= 0 :
16
+ print ("Please enter a positive number greater than 0." )
17
+ else :
18
+ sequence = collatz_sequence (num )
19
+ print ("\n Collatz sequence:" )
20
+ for i , value in enumerate (sequence , start = 1 ):
21
+ print (f"Step { i } : { value } " )
22
+ except ValueError :
23
+ print ("Invalid input! Please enter an integer." )
You can’t perform that action at this time.
0 commit comments