冰之一角

博客园 首页 新随笔 联系 订阅 管理

Project Euler 80 题目:

It is well known that if the square root of a natural number is not an integer, then it is irrational. The decimal expansion of such square roots is infinite without any repeating pattern at all.

The square root of two is 1.41421356237309504880..., and the digital sum of the first one hundred decimal digits is 475.

For the first one hundred natural numbers, find the total of the digital sums of the first one hundred decimal digits for all the irrational square roots.

求前一百个自然数(且平方根为无理数)的平方根的一百位有效数字的和.

PYHHON 代码如下:

import math

def numSqrt(num):#开平方
 list = [int(math.sqrt(num))]
 iDiv = list[0]
 iMiddle = num - iDiv*iDiv
 iTick = 1
 while True:
  iMiddle *= 100
  iSub = iMiddle / (20*iDiv)
  if iSub*(20*iDiv+iSub) ==  iMiddle:
   list.append(int(iSub))
   break
  elif iSub*(20*iDiv+iSub) < iMiddle:
   iMiddle -= iSub*(20*iDiv+iSub)
   list.append(int(iSub))
   iDiv = iDiv*10 + iSub
  else:
   iMiddle -= (iSub-1)*(20*iDiv+iSub-1)
   list.append(int(iSub-1))
   iDiv = iDiv*10 + iSub - 1
  iTick += 1
  if iTick == 100:
   break
 return list
 
iMax = 100
iRecord = 0
for j in range(1,iMax+1):
 iNum = math.sqrt(j)
 if iNum % 1 == 0:
  continue
 iList = numSqrt(j)
 for i in iList:
  iRecord += i

print iRecord

算出2的平方根的前一百位有效数字的和是475,和题目中一样,但算前一百位自然数的结果是:40841.错误.

看了N久也看不出哪里有问题,哪位牛人帮帮忙,看是哪里的问题.


 

posted on 2011-03-15 16:04  耳东之井  阅读(324)  评论(3编辑  收藏  举报