欧拉3 Python.将质数放入列表 [英] Euler 3 Python. Putting the prime numbers into a list

查看:224
本文介绍了欧拉3 Python.将质数放入列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对python还是很陌生,我正在尝试将600851475143中的所有素数都放入列表中.但是,我一直在列表中得到随机的数字而不是质数.我不太确定我要去哪里错.谢谢您的时间

Im still pretty new to python and I'm trying to get all of the prime numbers from 600851475143 into a list. However, I keep getting a random assortment of numbers in the list instead of the prime numbers. I'm not really sure where I am going wrong. Thank you for your time

import math
factors_list = []
prime_factors = []

def number_factors(s):
    s = int(math.sqrt(s))
    for num in range(2, s):
        for i in range(2, num):
            if (num % i) == 0:
                factors_list.append(num)
            else:
                prime_factors.append(num)

number_factors(600851475143)

print factors_list
print prime_factors

推荐答案

当前,您每次if (num % i) == 0都附加到prime_factor.因此,例如,如果num=12(不是素数)和i=5,则将附加到prime_factor.

Currently you append to prime_factor every time if (num % i) == 0. So, for example, if num=12 (not prime), and i=5 you'll do the append to prime_factor.

相反,只有在除数完全没有的情况下才应追加,而不仅仅是一个数字不能平均除.

Instead, you should only append if it has no divisors at all, not just a single number doesn't divide evenly.

不过,我会提前警告您,这个问题不仅与计算质数有关,而且600851475143是一个很大的数.因此,您可能应该将当前的代码作为学习练习,但是您需要重新考虑采用完整解决方案的方法.

I'll warn you ahead of time though, this problem is not only about calculating prime numbers, but that 600851475143 is a very large number. So you should probably get your current code working as a learning exercise, but you'll need to rethink your approach to the full solution.

这篇关于欧拉3 Python.将质数放入列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆