【问题标题】:Correctly compute square root digital expansions正确计算平方根数字展开
【发布时间】:2015-07-24 11:37:46
【问题描述】:

Project Euler's problem number 80 读作:

众所周知,如果自然数的平方根不是 整数,那么它是无理数。这种平方的十进制展开 根是无限的,根本没有任何重复的模式。

二的平方根是1.41421356237309504880...,数字 前一百位小数的总和是475

对于前一百个自然数,求总和 所有的前一百个十进制数字的数字和 无理数平方根。

这是我为这个问题生成的代码:

from decimal import *

from math import sqrt

getcontext().prec = 100


def digitalsum(n):
    sum = 0
    for a in n:
        sum += int(a)
    return sum
total = 0
for a in range(1, 101):
    if not sqrt(a) % 1 == 0:
        ans = str(Decimal(a).sqrt())
        ans = ans[2::]
        print(a)
        print(digitalsum(ans))
        print("-------")

        total += digitalsum(ans)
print(total)

它显示了错误的答案,我想我在此过程中错过了一些东西。任何形式的帮助表示赞赏。

【问题讨论】:

    标签: python square-root


    【解决方案1】:
    • 问题确实不是说要忽略数字的整数部分。

    • 通过指定 100 个十进制数字的精度仅仅意味着在计算过程中将使用 100 个数字而不是您将获得前 100 个精确的十进制数字。只需增加精度以确保计算产生至少 100 个正确数字:

      getcontext().prec = 102
      

      使用101 不足以得到正确答案。

    • 另外,您必须正确获取小数位数:

      ans = str(Decimal(a).sqrt()).replace('.', '')[:100]
      
    • 最后,前 100 个自然数从 099(含)1100(含)。

    所以你的代码会变成:

    from decimal import *
    
    from math import sqrt
    
    getcontext().prec = 102
    
    
    def digitalsum(n):
        sum = 0
        for a in n:
            sum += int(a)
        return sum
    
    total = 0
    
    for a in range(100):
        if not sqrt(a) % 1 == 0:
            ans = str(Decimal(a).sqrt()).replace('.', '')[:100]
            print(a)
            print(digitalsum(ans))
            print("-------")
    

    这会产生正确的答案。

    代码可以大大改进和缩短:

    from __future__ import print_function    #for python2 compatibility.
    
    from math import sqrt
    from decimal import Decimal, getcontext
    
    
    getcontext().prec = 102
    
    total = 0
    for a in range(100):
        if not sqrt(a) % 1 == 0:
            ans = str(Decimal(a).sqrt()).replace('.', '')[:100]
            digits = map(int, ans)
            print(a, sum(digits), "--------", sep='\n')
    
            total += sum(digits)
    print(total)
    

    【讨论】:

    • 为什么getcontext().prec = 101不够用?
    • @abaldwin99 试试看,你会看到它返回一个错误的答案。 要获得x 的确切数字,您只需要在计算期间使用x+1 数字即可,这与您进行了多少次计算以及发生了哪些操作无关。在这种情况下,使用 102 可以使事情正常进行。我开始使用120,然后寻找给出正确答案的最小数字。
    • @abaldwin99 因为sqrt(5) 等于2.23...4970..." rounded to 101 digits it becomes 2.23...50, but rounded to 102 digits it becomes 2.23...497` - 差异使得第 100 位不同。
    猜你喜欢
    • 2021-08-03
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多