原題:
編寫一個名為collatz()的函數(shù)麦撵,它有一個名為number 的參數(shù)琅束。如果參數(shù)是偶數(shù)科展,那么collatz()就打印出number // 2诈嘿,并返回該值堪旧。如果number 是奇數(shù),collatz()就打印并返回3 * number + 1奖亚。
然后編寫一個程序淳梦,讓用戶輸入一個整數(shù),并不斷對這個數(shù)調(diào)用collatz()昔字,直到函數(shù)返回值1(令人驚奇的是爆袍,這個序列對于任何整數(shù)都有效,利用這個序列,你遲早會得到1螃宙!既使數(shù)學(xué)家也不能確定為什么。你的程序在研究所謂的“Collatz序列”所坯,它有時候被稱為“最簡單的谆扎、不可能的數(shù)學(xué)問題”)。
先來看看wiki上對Collatz 序列的描述
Take any positive integer n. If n is even, divide it by 2 to get n / 2. If n is odd, multiply it by 3 and add 1 to obtain 3n + 1. Repeat the process indefinitely. The conjecture is that no matter what number you start with, you will always eventually reach 1.
也就是說實際上芹助,我們的限制條件需為正整數(shù)
答案如下:
#!/usr/bin/env python
# coding=utf-8
import sys
def collatz(number):
if number % 2 == 0:
return number // 2
else:
return 3 * number + 1
if __name__ == '__main__':
number =input('Enter positive number: ')
try:
number = int(number)
if number > 0:
while True:
if number != 1 :
print(collatz(number))
number = collatz(number)
else:
break
else:
print('you need input positive number.')
except:
print('you need input positive number.')
隨便測試幾個數(shù)
C:\python\learn07>python collatz.py
Enter positive number: 99
298
149
448
224
112
56
28
14
7
22
11
34
17
52
26
13
40
20
10
5
16
8
4
2
1
C:\python\learn07>python collatz.py
Enter positive number: 1
C:\python\learn07>python collatz.py
Enter positive number: 0
you need input positive number.
C:\python\learn07>python collatz.py
Enter positive number: -8
you need input positive number.
C:\python\learn07>python collatz.py
Enter positive number: 8sd
you need input positive number.