Respuesta :
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.")
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).
Answer:
Check the explanation
Explanation:
Just the way it is specified in the question above, I have taken the input x from the command line as well as making use of that input I calculated iterations that are required to converge to 1 in conjecture function.
Going to the conjecture function, I utilized the count variable to store the number of iterations and returned at the end of the function and at the end printed the output.
The Code:-
#importing sys
import sys
#function
def conjecture(n):
#count to store no of iterations
count=0
#loop run until n is equal to 1
while n!=1:
#if n is even
if n%2==0:
n=n/2
else: #if n is odd
n=3*n+1
#increment counter
count=count+1
return count
if __name__=="__main__":
#command line argument
x=int(sys.argv[1])
#calling function
n=conjecture(x)
#printing output
print("with an input of",x,"we converged to 1 after",n,"iterations.")