python编程计算前30项的和_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~62616964757a686964616fe78988e69d8331333332636366

#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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值