简体   繁体   English

使用Python的Euler项目#3(后续活动)

[英]Project Euler #3 with Python (Followup)

I'm working on problem #3 on project euler, and I've run into a problem. 我正在研究项目euler的问题#3,但是遇到了问题。 It seems that the program is copying all the items from factors into prime_factors , instead of just the prime numbers. 看来程序正在将所有项目从factors复制到prime_factors ,而不仅仅是质数。 I assume this is because my is_prime function is not working properly. 我认为这是因为我的is_prime函数无法正常工作。 How can I make the function do what I want? 我怎样才能让函数做我想要的? Also, in the code, there is a line that I commented out. 另外,在代码中,我注释掉了一行。 Do I need that line, or is it unnecessary? 我需要那条线,还是不必要? Finally, is the code as a whole sound (other than is_prime ), or is it faulty? 最后,代码是整体声音(不是is_prime ),还是有问题?

The project euler question is: The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? 项目欧拉问题是:13195的素数是5、7、13和29。600851475143的最大素数是多少?

A link to a previous question of mine on the same topic: https://stackoverflow.com/questions/24462105/project-euler-3-python?noredirect=1#comment37857323_24462105 指向同一主题的我先前的问题的链接: https : //stackoverflow.com/questions/24462105/project-euler-3-python?noredirect=1#comment37857323_24462105

thanks 谢谢

import math
factors = []
prime_factors = []
def is_prime (x):
    counter = 0
    if x == 1:
        return False
    elif x == 2:
        return True
    for item in range (2, int(x)):
        if int(x) % item == 0:
            return False
        else:
            return True
number = int(input("Enter a number: "))
start = int(math.sqrt(number))
for item in range(2, start + 1):
    if number % item == 0:
        factors.append(item)
        #factors.append(number/item)   do i need this line?
for item in factors:
    if is_prime(item) == True:
        prime_factors.append(item)
print(prime_factors)

Yes, you need the commented line. 是的,您需要带注释的行。

(It seems that on that case it's not necessary, but with other numbers the part of your code for getting factors would go wrong). (似乎在这种情况下没有必要,但是使用其他数字,获取因子的代码部分将出错)。

Check these references: 检查这些参考:

Prime numbers 质数

Integer factorization 整数分解

Why do we check up to the square root of a prime number to determine if it is prime or not 我们为什么要检查质数的平方根以确定它是否为质数

I got a very fast result on my computer with the following code: 使用以下代码,我在计算机上得到了非常快的结果:

#!/usr/bin/env python
import math

def square_root_as_int(x):
  return int(math.sqrt(x))

def is_prime(number):
  if number == 1:
    return False
  for x in range(2, square_root_as_int(number) + 1):
    if x == number:
      next
    if number % x == 0:
      return False
  return True

def factors_of_(number):
  factors = []
  for x in range(2, square_root_as_int(number) + 1):
    if number % x == 0:
      factors.append(x)
      factors.append(number/x)
  return factors

factors = factors_of_(600851475143)
primes = []
for factor in factors:
  if is_prime(factor):
    primes.append(factor)
print max(primes)

# Bonus: "functional way"
print max(filter(lambda x: is_prime(x), factors_of_(600851475143)))

Your is_prime() returns early. 您的is_prime()提前返回。 Here's a fixed version: 这是固定版本:

def is_prime (x):
    if x == 1:
        return False
    if x == 2:
        return True
    for item in range (2, int(x)):
        if int(x) % item == 0:
            return False
    return True

you should not be using int(x) in the way that you currently are. 您不应该以目前的方式使用int(x) i know you're forcing the int type because you want to convert from string input, but this will also allow the user to enter a float (decimal), and have it interpreted as either prime or not. 我知道您要强制使用int类型,因为您要从字符串输入进行转换,但这也将允许用户输入浮点数(十进制),并将其解释为素数或非素数。 that is bad behavior for the function. 这是该功能的不良行为。 see my solution below. 请在下面查看我的解决方案。 if you use eval to verify the input, you can just use x later, in place of int(x) . 如果使用eval验证输入,则可以稍后使用x代替int(x)

import math
factors = []
prime_factors = []
def is_prime (x):
    x = eval(x) # this will cause a string like '5' to be evaluated as an integer. 
                # '5.2' will be evaluated as a float, on the other hand.
    if type(x) != int: 
         raise Exception('Please enter an integer.') #prevents bad input
    counter = 0 #this counter is not used. why is it initialized here?
    if x == 1:
        return False
    elif x == 2: 
        return True
    for item in range (2, x): 
        if x % item == 0:
            return False
        else:
            return True

Use the while loop. 使用while循环。 n%i simply means n%i!=0 n%i只是意味着n%i!= 0

i = 2
n = 600851475143
while i*i <= n:
   if n%i:
          i+=1
   else:
          n //= i

print n

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM