Answer:
- import sys
-
- def conjecture(n):
- count = 0
- while(n != 1):
- if(n % 2 == 0):
- n = n//2
- else:
- n = (n * 3) + 1
- count += 1
- return count
-
- if __name__ == "__main__":
- n = sys.argv
- c = conjecture(int(n[1]))
- print("With an input of",n[1],"we converged to 1 after",c,"iterations.")
Step-by-step explanation:
Firstly, we work on conjecture function. Create a counter variable, count to track the number of iteration needed to converge n to 1 (Line 4).
Create a while loop and set the condition so long as n not equal to 1 the loop will keep running (Line 5). In the loop, if the n is divisible by 2 (even), divide the n by 2 (Line 6-7). Otherwise, multiply n by 3 and add 1 (Line 8-9). Increment count by one before proceeding to next loop (Line 10).
At last return the count as output (Line 11).
In the main program, we use sys.argv to get the input value from command line (Line 14). Pass the second element of the input from command line to the function and create a variable c to capture the function output (Line 15 ). At last, print the input number and output from the function (Line 16).