Euler 4,Modulo问题

时间:2017-03-13 19:54:07

标签: python-3.x

新手程序员刚从代码学院毕业。我想继续这样,所以我开始了欧拉的例子。我已经到了4号,https://projecteuler.net/problem=4

我的程序很满意地得到了数字980089,但是确定这个数字可以被994整除。但是另一个值实际上是986.0050302。这不是我正在寻找的答案。因此模数不能正常工作,因为剩余的为0.0050302。为什么会这样?

完整代码:

x = 999998
g = 2
while g < 99:
    e = str(x)
    if e[::-1] == str(x):
        print(e)
        for f in reversed(range(100, 1000)):
            f = float(f)
            h = x/f
            if int(x) % f == 0.000000 and h < 1000:
                print("%s and %s" % (f, h))
                break
            else:
                x = x - 1
    else:
        x = x - 1

关于如何改进我的代码的提示也很棒,我不认为我的命令是我最初想象的那样。

1 个答案:

答案 0 :(得分:0)

看起来你想要做的一般想法是从比两个3位数字可以乘以的任何数字开始的数字开始,然后开始向下看,看看是否有任何可能的3 -digit数字将乘以您当前的数字。

我注意到的第一件事是你的while循环使用g,但是你永远不会在你的循环中修改它,所以它相当无用。我还注意到你一次使用xint(x)转换为int,这是不需要的,因为x总是已经是int。

我将尝试重写您的代码以做正确的事情 - 如果您对此有任何疑问,请与我联系!

x = 999998
found_an_answer = False    

# We'll certainly find an answer before we get here
while x > 10000:

    # get the string version of the number
    x_string = str(x)

    # See if its the same as its reverse
    if x_string == x_string[::-1]:

        # Print out the palindrome we're currently looking at
        print ("Looking for 3-digit factors of " + x_string)

        # Let's try all the factors from 999 to 100
        for f in reversed(range(100, 1000)):

            # First, check if f is a factor of x by checking if the
            #  remainder is 0 when we divide x by f.
            # Then, check if the other factor, x/f, is less than 1000
            #  to make sure it is three digits
            if x%f == 0 and x/f < 1000:

                # If we made it here, we found the number!!
                print("Found the number!")
                print("Number: {}".format(x))
                print("Factors: {}, {}".format(f, x/f))

                # We set this to be true because using a "break"
                # statement will only break out of the inner most
                # loop (the one where we're modifying f
                found_an_answer = True
                break

        # Now that we left the inner loop, we can check the
        #  found_an_answer variable to see if we should
        #  break out of the outer loop to.
        if found_an_answer:
            break

    # Guess we didn't find an answer yet.  LEt's look at the next
    #  smallest number.
    x = x-1

还有一件小事 - 而不是使用while循环并手动减少其中的x,你可以通过将循环更改为

来执行for循环倒计时
for x in range(999998, 10000, -1):

然后您不需要x=999998行或x = x-1行。