1、python编程2/1+3/2+5/3+8/5+13/8+……前50项和

如题所述

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

温馨提示:内容为网友见解,仅供参考
第1个回答  2013-10-23
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本回答被提问者采纳
第2个回答  2013-10-23
x=1.0;y=2.0;ret=0
for i in range(50):
    ret+=y/x
    t=y
    y+=x
    x=t
print ret

相似回答