[英]How do I make it so it can loop?
I need to test whether n is a multiple of 2 and then divide the number by 2. If the number isn't a multiple of 2, then I have to do 3*n+2.我需要测试n是否是2的倍数,然后将数字除以2。如果数字不是2的倍数,那么我必须做3 * n + 2。
How do I make it loop so I can get the following: 12, 6, 3, 10, 5, 16, 8, 4, 2, 1?如何使其循环,以便获得以下信息:12、6、3、10、5、16、8、4、2、1?
Here's my current code:这是我当前的代码:
n=12
while n!=0:
if n%2==0:
print (n)
n=n/2
if n!=n%2:
if n !=1:
n = 3*n+2
else:
break
print(n)
First of all your formula of 3*n + 2
will lead to infinite loop.首先,您的
3*n + 2
公式将导致无限循环。 According your sample output, it needs to be 3*n + 1
.根据您的样品 output,它需要是
3*n + 1
。
n = 12
while n >= 1:
print(n, end=' ')
if n == 1:
break
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
First note is that it is 3*n+1, second one is that you have to write n=n/2 in your first if.第一个注意是它是 3*n+1,第二个是你必须在你的第一个 if 中写 n=n/2。
Overall this code is what you want:总的来说,这段代码就是你想要的:
n = 12
while n != 0:
if n % 2 == 0:
print(n, end=' ')
n = n / 2
elif n % 2 != 0:
if n != 1:
print(n, end=' ')
n = 3 * n + 1
else:
print(1)
break
Or this:或这个:
n = 12
while n > 1:
if n % 2 == 0:
print(n, end=' ')
n = n / 2
elif n % 2 != 0:
if n != 1:
print(n, end=' ')
n = 3 * n + 1
else:
print(1)
Good luck祝你好运
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.