python - 给出一个大数字作为参数后,函数不会返回任何内容

标签 python python-3.x

我正在通过做Project Euler来学习Python问题,我被困在 Problem #3 .

我想我已经找到了一个可行的解决方案,但是当插入大数字 600851475143 时,它只是不返回任何内容。我相信它只是加载和加载,因为即使使用 6008514,也需要 10 秒才能返回答案。

# What is the largest prime factor of the number x?
import math

def isPrime(x):
    try:
        sqr = math.sqrt(x)
        if x == 0 or x == 1:
            return 0

        for n in range (2 , int(sqr)+1):
            if x % n == 0:
                return 0
        return 1
    except:
        return 'Give positive numbers.'

def largestPrimeFactor(x):
    if isPrime(x) == 1:
        return 'This number is prime.'
    else:
        largest = -1
        mid = x/2
        for n in range(2,int(mid)+1):
            if isPrime(n):
                if x % n == 0:
                    largest = n

        if largest == -1:
            return 'Enter numbers above 1.'
        else:            
            return largest

print(largestPrimeFactor(600851475143))

最佳答案

这段代码应该可以工作:

    import math

    def isPrime(x):
        try:
            sqr = math.sqrt(x)
            if x == 0 or x == 1:
                return 0
            n = 2
            highest = x
            while n < highest:
                if x%n ==0:
                    return 0
                highest = x/ n
                n +=1
            return 1
        except:
            return 'Give positive numbers.'

    def largestPrimeFactor(x):
        if isPrime(x) == 1:
            return 'This number is prime.'
        n = 2
        highest = x
        largest = 1
        while n < highest:
            if x%n == 0:
                if isPrime(n):
                    largest = n
            highest = x/n
            n +=1
        return largest


    print(largestPrimeFactor(600851475143))

我做了一个优化: 您检查是否每个数字都是 x 的因数,而如果例如 2 不是 x 的因数,则确定 x 的最大因数可以是 x/2。因此,如果 n 不是 x 的因子,则 x 的最大可能因子只能是 x/n。

关于python - 给出一个大数字作为参数后,函数不会返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60956231/

相关文章:

python - 以编程方式在 pytest 插件中注册固定装置

python - 随机日期和月份,但保留年份和时间间隔

python-3.x - 使用 ctypes 获取可用工作区

python - 将两个变量添加到 QComboBox

python-3.x - 轴上的数据未按预期顺序排列

python - 你如何找到两个列表之间的公共(public)子列表?

python - 在Python(在Mac上)中读取文件时,打印输出的文本不正确

python - 计算 2 个 pandas 数据帧中的匹配数

python - 更改数据库后 Django 上的内部服务器错误

python - 为什么 shutils 和 df 报告的磁盘大小有几个百分比的差异?