Well, 'cause I noticed that some of the number can't be divided exactly,
so I thought keeping the result as a fraction would be more accurate.
But after done writing, I found it's not that valuable to use fraction,
the number would get huge because there's not manycommon factors between the nominator and denominator.
My code is here, just for reference~
#2/1 + 3/2 + 5/3 + 8/5 + ... ...
#Some number can't be divided exactly. Use fraction to keep the result.
#
#get all factors of a number
def getFactors(num):
facList = []
while num % 2 == 0:
facList.append(2)
num /= 2
limit = int(num**(0.5)+1)
for i in range(3,limit+2, 2):
if num % i == 0:
facList.append(i)
num /= i
facList.append(num)
return facList
# n is nominator, dList is the factor list of denominator.
def factor(n, d, dList):
for i in dList:
if n % i == 0:
n /= i
d /= i
dList.remove(i)
return n,d,dList
if __name__ == '__main__':
d = 2 #denominator
n = 3 #nominator
#beginning number is 2/1
dRes = 1
nRes = 2
#recording denominator's factors.
dFactorList = []
for i in range(49):
#print nRes , dRes, n,d,
nRes = nRes*d+n*dRes
dRes = dRes*d
#record factor of d
dFactorList.extend(getFactors(d))
#Use common factor to shrink the recorded number (nRes/dRes)
nRes, dRes, dFactorList = factor(nRes, dRes, dFactorList)
t = d
d = n
n = t+n
print nRes, '/', dRes , nRes*1.0/dRes
a=1.0
b=2.0
sum=0.0
c=0.0
for i in range(0,50):
sum= sum+ b/a
c= a+b
a= b
b= c
print sum
我主要是写JAVA,也是刚开始学习python
x=1.0;y=2.0;ret=0
for i in range(50):
ret+=y/x
t=y
y+=x
x=t
print ret