简体   繁体   中英

How do I solve this problem with while loop

c0=int(input("enter a number here"))

Question:

  1. take any non-negative and non-zero integer number and name it c0;
  2. if it's even, evaluate a new c0 as c0 ÷ 2;
  3. otherwise, if it's odd, evaluate a new c0 as 3 × c0 + 1;
  4. if c0 ≠ 1, skip to point 2
  5. Write a program which reads one natural number and executes the above steps as long as c0 remains different from 1
  6. We also want you to count the steps needed to achieve the goal. Your code should output all the intermediate values of c0, too.

My code:

c01=c0%2
c02=3*c0+1
while c0!=1:
    if c01==0:
        print(c01)
    else:
        print(c02)
    c0+=1
print("total number steps",)

Sample input: 16

Expected output:

8
4
2
1
steps = 4
while True:
    c0 = int(input("Enter a Number Here: "))
    if c0 > 0:
        break
    else:
        continue

count = 0

while c0 != 1:
    if c0 % 2 == 0:
        c0 = c0 / 2
        print("{} ".format(int(c0)))
    else:
        c0 = 3 * c0 + 1
        print("{} ".format(int(c0)))
    count += 1

print("Steps: {}".format(count))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM